text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Tags: binary search, number theory Correct Solution: ``` n,m = [int(i) for i in input().split()] l = [] for i in range(1,int(n**0.5)+1): if n%i == 0 and m%i == 0: l.append(i) if n%(n//i) == 0 and m%(n//i) == 0: l.append(n//i) l.sort() n = int(input()) for i in range(n): q,w = [int(j) for j in input().split()] mx = -1 for j in range(len(l)-1,-1,-1): if q<=l[j]<=w: mx = l[j] break print(mx) ```
94,900
Provide tags and a correct Python 3 solution for this coding contest problem. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Tags: binary search, number theory Correct Solution: ``` import math,bisect a,b=map(int,input().split()) gcd=math.gcd(a,b) arr=[i for i in range(1,int(math.sqrt(gcd))+1) if gcd%i==0] for i in arr[::-1]:arr.append(gcd//i) for _ in range(int(input())): l,h=map(int,input().split()) idx=bisect.bisect(arr,h)-1 if l>arr[idx]:print(-1) else:print(arr[idx]) ```
94,901
Provide tags and a correct Python 3 solution for this coding contest problem. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Tags: binary search, number theory Correct Solution: ``` def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) divisors.sort() return divisors a, b = map(int, input().split()) n = int(input()) import math g = math.gcd(a, b) D = make_divisors(g) import bisect for i in range(n): low, high = map(int, input().split()) l = bisect.bisect_left(D, low) r = bisect.bisect_right(D, high) if l != r: print(D[r-1]) else: print(-1) ```
94,902
Provide tags and a correct Python 3 solution for this coding contest problem. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Tags: binary search, number theory Correct Solution: ``` from functools import reduce import io,os,sys,math def binarySearchkeeb(data,target,low,high): if low > high: return high else: mid=(low+high)//2 if data[mid] <=target: return binarySearchkeeb(data,target,mid+1,high) else: return binarySearchkeeb(data,target,low,mid-1) input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def gcd(x,y):return math.gcd(x,y) def allFactors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) a,b=map(int,input().split()) re=sorted(allFactors(gcd(a,b))) for _ in range(int(input())): l,h=map(int,input().split()) ans=binarySearchkeeb(re,h,0,len(re)-1) if ans == -1: print(-1) else: c=re[ans] if l <= c: print(c) else: print(-1) ```
94,903
Provide tags and a correct Python 3 solution for this coding contest problem. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Tags: binary search, number theory Correct Solution: ``` # import sys # sys.stdin = open("input.in","r") from sys import stdin input = stdin.readline from heapq import heapify,heappush,heappop,heappushpop from collections import defaultdict as dd, deque as dq,Counter as C from math import factorial as f ,ceil,gcd,sqrt,log from bisect import bisect_left as bl ,bisect_right as br from itertools import combinations as c,permutations as p from math import factorial as f ,ceil,gcd,sqrt,log mp = lambda : map(int,input().split()) it = lambda: int(input()) ls = lambda : list(input().strip()) def isprime(n): for j in range(3,int(sqrt(n))+1,2): if n%j==0: return 0 return 1 def factors(n): s = set() s.add(1) s.add(n) for j in range(2,int(sqrt(n))+1): if n%j==0: s.add(j) s.add(n//j) return s a,b = mp() k = sorted(factors(a)) for _ in range(it()): l,h = mp() ans =-1 for el in range(br(k,h)-1 ,bl(k,l)-1,-1): if b%k[el]==0: ans = k[el] break if ans>=l and ans<=h: print(ans) else: print(-1) ```
94,904
Provide tags and a correct Python 3 solution for this coding contest problem. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Tags: binary search, number theory Correct Solution: ``` from math import gcd from bisect import bisect a,b=map(int,input().split()) d=gcd(a,b) c=int(d**0.5) m=[] for i in range(1,c+1): if d%i==0: m.append(i) m.append(d//i) m.sort() n=int(input()) for i in range(n): c,d=map(int,input().split()) e=bisect(m,c) f=bisect(m,d) y=0 for i in range(f-1,e-2,-1): if m[i]>=c and m[i]<=d: print(m[i]) y=1 break if y==0: print("-1") ```
94,905
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` from math import sqrt def bin_ser(co_szuk): start, koniec = 0, len(dzielniki) - 1 while start < koniec: srodek = (koniec + start + 1) // 2 if dzielniki[srodek] > co_szuk: koniec = srodek - 1 else: start = srodek return dzielniki[start] def nwd(a, b): while b: a, b = b, a % b return a a, b = map(int, input().split()) NWD = nwd(a,b) dzielniki = [] for i in range(1, int(sqrt(NWD)) + 1): if NWD % i == 0: dzielniki.append(i) if i * i != NWD: dzielniki.append(NWD // i) dzielniki.sort() for t in range(int(input())): low, high = map(int, input().split()) wynik = bin_ser(high) if wynik <= high and wynik >= low: print(wynik) else: print(-1) ``` Yes
94,906
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` import sys lines = sys.stdin.readlines() (m, n) = map(int, lines[0].strip().split(" ")) def gcd(a, b): if a == 0: return b if a > b: return gcd(b, a) return gcd(b%a, a) G = gcd(m, n) tmp = G factors = [] i = 2 while i**2 <= tmp: if tmp % i == 0: factors.append(i) tmp//=i else: i += 1 if tmp != 1: factors.append(tmp) count = {} for f in factors: if f not in count: count[f] = 0 count[f] += 1 primes = list(count.keys()) primes.sort() factors = [1] for p in primes: tmp = [] for f in factors: for i in range(1, count[p]+1): tmp.append(f * p ** i) factors += tmp factors.sort() L = len(factors) Q = int(lines[1].strip()) for q in range(2, Q+2): (lo, hi) = map(int, lines[q].strip().split(" ")) l, r = 0, L while l < r-1: mid = (r-l)//2 + l if factors[mid] > hi: r = mid else: l = mid if factors[l] >= lo: print(factors[l]) else: print(-1) ``` Yes
94,907
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(10**4) from math import ceil,factorial,floor,gcd,log2,log10,sqrt from collections import defaultdict as dd,Counter as cc,deque from itertools import permutations as perm, combinations as comb from heapq import heapify,heappush,heappushpop,nlargest,nsmallest from bisect import bisect_left,bisect_right,bisect as bs inpl=lambda : list(map(int,input().split())) lstinp=lambda : list(input().split()) inpm=lambda : map(int,input().split()) inps=lambda :int(input()) inp=lambda : input() def Divisors(n) : l=[] i = 2 while i <= sqrt(n): if (n % i == 0) : if (n // i == i) : l.append(i) else : l.append(i) l.append(n//i) i = i + 1 return l def SieveOfEratosthenes(n): l=[] 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]: l.append(p) return l def primeFactors(n): l=[] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3,int(sqrt(n))+1,2): while n % i== 0: l.append(i) n = n / i if n > 2: l.append(n) return(l) def Factors(n) : result = [] for i in range(2,(int)(sqrt(n))+1) : if (n % i == 0) : if (i == (n/i)) : result.append(i) else : result.append(i) result.append(n//i) result.append(1) result.append(n) return result def maxSubArraySum(a): max_so_far = 0 max_ending_here = 0 size=len(a) for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def longestsubarray(arr, n, k): current_count = 0 # this will contain length of # longest subarray found max_count = 0 for i in range(0, n, 1): if (arr[i] % k != 0): current_count += 1 else: current_count = 0 max_count = max(current_count,max_count) return max_count def main(): a,b=inpm() gg=gcd(a,b) fact=sorted(Factors(gg)) q=inps() for _ in range(q): l,r=inpm() if l>gg: print(-1) continue if r>gg: r=gg x=fact[bisect_right(fact,r)-1] if x in range(l,r+1): print(x) else: print(-1) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ``` Yes
94,908
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` from fractions import gcd a, b = map(int, input().split(' ')) x = gcd(a, b) div = [] for i in range(1, int(x**0.5+1)): if x%i==0: if i*i==x: div.append(i) else: div.append(i) div.append(x//i) div.sort() lenx = len(div) for i in range(int(input())): a, b = list(map(int, input().split(' '))) lo = 0 hi = lenx-1 work = -1 while lo <= hi: mid = (lo + hi) // 2 if div[mid] < a: lo = mid+1 elif div[mid] > b: hi = mid - 1 else: work = max(work, div[mid]) lo = mid + 1 print(work) ``` Yes
94,909
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` import math,sys from collections import Counter, defaultdict, deque from sys import stdin, stdout input = stdin.readline lili=lambda:list(map(int,sys.stdin.readlines())) li = lambda:list(map(int,input().split())) #for deque append(),pop(),appendleft(),popleft(),count() I=lambda:int(input()) S=lambda:input().strip() mod = 1000000007 a,b=li() a,b=min(a,b),max(a,b) ans=[] for i in range(1,int(math.sqrt(b)+1)): if(a%i==0 and b%i==0): ans.append(i) if(b%a==0): ans.append(a) #print(*ans) for i in range(I()): l,r=li() f=0 for j in ans[::-1]: if(l<=j and j<=r): f=1 print(j) break if(not f): print(-1) ``` No
94,910
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` import math,sys from collections import Counter, defaultdict, deque from sys import stdin, stdout input = stdin.readline li = lambda:list(map(int,input().split())) def factors(g): fact=[] for i in range(1,int(math.sqrt(g))+1): if(g%i==0): if(i*i==g): fact.append(i) else: fact.append(i) fact.append(g//i) fact.sort(reverse=True) # print(*fact) return(fact) def case(): a,b=li() g=math.gcd(a,b) print(g) fact=factors(g) q=int(input()) for i in range(q): l,r=li() flag=0 for j in range(len(fact)): if(fact[j]<=r and fact[j]>=l): print(fact[j]) flag=1 break if(not flag): print(-1) for _ in range(1): case() ``` No
94,911
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` from math import gcd a,b=map(int,input().split()) c=gcd(a,b) c=int(c**0.5) m=[] for i in range(1,c+1): if c%i==0: m.append(i) m.append(b//i) m.sort(reverse=True) n=int(input()) for i in range(n): c,d=map(int,input().split()) y=0 for i in m: if i>=c and i<=d: print(i) y=1 break if y==0: print("-1") ``` No
94,912
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. Input The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109). Output Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Examples Input 9 27 3 1 5 10 11 9 11 Output 3 -1 9 Submitted Solution: ``` a, b = map(int, input().split()) import math g = math.gcd(a, b) lis = [i for i in range(1, g+1) if g%i == 0] print(lis) n = int(input()) for _ in range(n): a, b = map(int , input().split()) if a > g: print(-1) else: bo = 1 for i in range(b, a-1, -1): if i in lis: print(i); bo = 0 if bo: print(-1) ``` No
94,913
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` N = int( input() ) X = list( map( int, input().split() ) ) V = list( map( int, input().split() ) ) def calc( p ): # everyone is gathered to point p return max( abs( X[ i ] - p ) / V[ i ] for i in range( N ) ) lb, ub = 1.0, 1e9 while ub - lb > 5e-7: mid = ( lb + ub ) / 2 if calc( mid - 5e-7 ) < calc( mid + 5e-7 ): ub = mid else: lb = mid print( "%.9f" % calc( lb ) ) ```
94,914
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` n=int(input()) x=[int(x) for x in input().split()] v=[int(x) for x in input().split()] def fin(h): return max(abs(h-x[i])/v[i] for i in range(n)) l,r=1.0,1e9 while r-l>5e-7: mid=(l+r)/2 if (fin(mid-4e-7)<fin(mid+4e-7)): r=mid else: l=mid print(fin(l)) ```
94,915
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` def f(t): a = (x[0] - v[0] * t) * 1.0 b = (x[n - 1] + v[n - 1] * t) * 1.0 for i in range(n): if x[i] - v[i] * t > a: a = x[i] - v[i] * t if x[i] + v[i] * t < b: b = x[i] + v[i] * t #print(a, b) return a <= b n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) inf = 1000000000.0 l = 0 r = inf while r - l > 1e-6: m = (l + r) / 2 if f(m): r = m else: l = m print(r) ```
94,916
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` from math import isclose n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) xx = list((x[i], v[i]) for i in range(n)) xx.sort() l, h = xx[0][0], xx[-1][0] m = (h + l) / 2 while not isclose(l, h): m = (h + l) / 2 t = abs(m - xx[0][0]) / xx[0][1] a, b = True, t for i in range(1, n): t2 = abs(m - xx[i][0]) / xx[i][1] if not isclose(t, t2): s = False if t2 > b: b = t2 a = bool(xx[i][0] < m) if a: h = m else: l = m print(max(abs(m - xx[i][0]) / xx[i][1] for i in range(n))) ```
94,917
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` from sys import stdin inp=stdin.readline n=int(inp()) d=[int(x) for x in inp().split()] v,big,small,t=[int(x) for x in inp().split()],max(d),min(d),0 while(big-small>10**-6): t=-1 mid=(big+small)/2 for i in range(n): if abs(d[i]-mid)/v[i]>t: t=abs(d[i]-mid)/v[i] x=d[i] if x>mid:small=mid else:big=mid print(t) ```
94,918
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` def main(n, x, v): eps = 1e-7 def f(p): nonlocal n, x, v t = 0.0 for i in range(n): t = max(t, abs(x[i] - p) / v[i]) return t low = 0 high = 1e9 while low + eps < high: mid = (high + low) / 2 midd = (mid + high) / 2 if f(mid) < f(midd): high = midd else: low = mid return f(low) print(main(int(input()), list(map(int, input().split(' '))), list(map(int, input().split(' '))))) ```
94,919
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` def check(f, speed, t): inter = (f[0] - speed[0] * t, f[0] + speed[0] * t) for i in range(1, len(f)): cur = (f[i] - speed[i] * t, f[i] + speed[i] * t) if cur[0] > inter[1] or inter[0] > cur[1]: return False else: inter = (max(cur[0], inter[0]), min(cur[1], inter[1])) return True def binsearch(fr, sp): inf = 0 sup = 10 ** 10 while sup - inf > 10 ** (-6): if check(fr, sp, (sup + inf) / 2): sup = (sup + inf) / 2 else: inf = (sup + inf) / 2 return inf if check(fr, sp, inf) else sup n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) print(binsearch(x, v)) ```
94,920
Provide tags and a correct Python 3 solution for this coding contest problem. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Tags: binary search Correct Solution: ``` def inputIntegerArray(): return list( map( int, input().split(" ") ) ) def time( t, pos, speed ): maxleft = 0 minright = 1000000000 for i in range(0,len(pos)): distance = speed[i]*t left = pos[i]-distance right = pos[i]+distance maxleft = max( maxleft, left ) minright = min( minright, right ) if ( maxleft <= minright ): return True else: return False (n) = inputIntegerArray() pos = inputIntegerArray() speed = inputIntegerArray() left = 0.0 right = 1000000000.0 for i in range(0,64): m = left + ( right - left )/2; if ( time( m, pos, speed ) ): right = m else: left = m print ( left ) ```
94,921
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) l, r = 0, 10 ** 10 t = (l + r) / 2 while r - l >= 10 ** -6: t = (l + r) / 2 max_l = -float('inf') min_r = float('inf') for i in range(n): left = x[i] - v[i] * t right = x[i] + v[i] * t max_l = max(max_l, left) min_r = min(min_r, right) if max_l <= min_r: r = t else: l = t print(t) ``` Yes
94,922
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` import sys input = sys.stdin.readline def judge(t): L, R = -10**18, 10**18 for xi, vi in zip(x, v): L = max(L, xi-t*vi) R = min(R, xi+t*vi) return L<=R def binary_search(): l, r = 0, 10**10 while r-l>=1e-7: mid = (l+r)/2 if judge(mid): r = mid else: l = mid return l n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) print(binary_search()) ``` Yes
94,923
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` from sys import stdin inp=stdin.readline n=int(inp()) d=[int(x) for x in inp().split()] v,big,small,t,c=[int(x) for x in inp().split()],max(d),min(d),0,40 while(c): mid,c,t=(big+small)/2,c-1,-1 for i in range(n): if abs(d[i]-mid)/v[i]>t: t=abs(d[i]-mid)/v[i] x=d[i] if x>mid:small=mid else:big=mid print(t) ``` Yes
94,924
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) l = 0; r = 1e9 + 1 for _ in range(1000): m = (l + r) * 0.5 L = -2e9; R = 2e9 for i in range(n): L = max(L, x[i] - v[i] * m) R = min(R, x[i] + v[i] * m) if R >= L: r = m else: l = m print(round((l + r) / 2, 10)) ``` Yes
94,925
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` def solve(t,x,v): l=[x[i]-v[i]*t for i in range(len(x))] r=[x[i]+v[i]*t for i in range(len(x))] return 1 if max(l)<=min(r) else 0 n=int(input()) x=list(map(int,input().split())) v=list(map(int,input().split())) l=0 h=10**9 cnt=0 while l<h and cnt<100: mid=l+(h-l)/2 print(mid) cnt+=1 if solve(mid,x,v): h=mid else: l=mid print(l) ``` No
94,926
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` n, x, v = int(input()), list(map(int, input().split())), list(map(int, input().split())) def f(pos): res = 0 for i in range(n): res = max(res, abs(pos - x[i]) / v[i]) return res l, r, m1, m2 = 1, 1e9, 0, 0 for _ in range(60): ln = r - l m1 = l + ln / 3 m2 = r - ln / 3 if f(m1) < f(m2): r = m2 else: l = m1 print("%.12f" % f(l)) ``` No
94,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` n = int(input()) x = list(map(float, input().split())) v = list(map(float, input().split())) def f(x0): global x global v global n d = 0 for i in range(n): d = max(d, abs(x0 - x[i]) / v[i]) return d l = 0 r = max(x) for i in range(70): m1 = (l + l + r) / 3 m2 = (l + r + r) / 3 if (f(m1) >= f(m2)): l = m1 else: r = m2 print(f(l)) ``` No
94,928
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. Input The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second. Output Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if <image> holds. Examples Input 3 7 1 3 1 2 1 Output 2.000000000000 Input 4 5 10 3 2 2 3 2 4 Output 1.400000000000 Note In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. Submitted Solution: ``` # n=int(input()) # n,k=map(int,input().split()) # arr=list(map(int,input().split())) #ls=list(map(int,input().split())) #for i in range(m): # for _ in range(int(input())): from collections import Counter #from fractions import Fraction import math n=int(input()) dis=list(map(int,input().split())) v=list(map(int,input().split())) l=0 r=10**9+100 while r-l>=10**-7: t=(l+r)/2 l2=0 r2=10**9 for i in range(n): x,y=dis[i]-v[i]*t,dis[i]+v[i]*t l2=max(x,l2) r2=min(y,l2) if l2<=r2: r=t else: l=t print(l) ``` No
94,929
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` import sys mod = 10**9 + 7 def solve(): n = int(input()) a = [int(i) for i in input().split()] cnt = [0]*(10**5 + 1) pat = [0]*(10**5 + 1) p2 = [1]*(n + 1) for i in range(1, n + 1): p2[i] = (2 * p2[i - 1]) % mod for ai in a: cnt[ai] += 1 for i in range(1, 10**5 + 1): for j in range(2*i, 10**5 + 1, i): cnt[i] += cnt[j] pat[i] = p2[cnt[i]] - 1 for i in range(10**5, 0, -1): for j in range(2*i, 10**5 + 1, i): pat[i] = (pat[i] - pat[j]) % mod ans = pat[1] % mod print(ans) if __name__ == '__main__': solve() ```
94,930
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory 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 prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod 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 for _ in range(int(input()) if not True else 1): n = int(input()) #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() mod = 10**9 + 7 twopow = [1]*(10**5+69) for i in range(1, 10**5+69): twopow[i] = (twopow[i-1] * 2) % mod count = [0]*100069 for i in a: count[i] += 1 multiples = [0]*100069 for i in range(1, 10**5+1): for j in range(i, 10**5+1, i): multiples[i] += count[j] gcd_of = [0]*100069 for i in range(10**5, 0, -1): gcd_of[i] = (twopow[multiples[i]] - 1) % mod for j in range(2*i, 10**5+1, i): gcd_of[i] -= gcd_of[j] print(gcd_of[1] % mod) ```
94,931
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` n=int(input()) r=list(map(int,input().split())) dp=[0]*(10**5+1) cnt=[0]*(10**5+1) tmp=[0]*(10**5+1) mod=10**9+7 for i in range(n): cnt[r[i]]+=1 for i in range(1,10**5+1): for j in range(2*i,10**5+1,i): cnt[i]+=cnt[j] tmp[i]=pow(2,cnt[i],mod)-1 for i in range(10**5,0,-1): for j in range(2*i,10**5+1,i): tmp[i]=(tmp[i]-tmp[j])%mod print(tmp[1]%mod) ```
94,932
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` MOD = int( 1e9 ) + 7 N = int( input() ) A = list( map( int, input().split() ) ) pow2 = [ pow( 2, i, MOD ) for i in range( N + 1 ) ] maxa = max( A ) mcnt = [ 0 for i in range( maxa + 1 ) ] mans = [ 0 for i in range( maxa + 1 ) ] for i in range( N ): mcnt[ A[ i ] ] += 1 for i in range( 1, maxa + 1 ): for j in range( i + i, maxa + 1, i ): mcnt[ i ] += mcnt[ j ] mans[ i ] = pow2[ mcnt[ i ] ] - 1 for i in range( maxa, 0, -1 ): for j in range( i + i, maxa + 1, i ): mans[ i ] = ( mans[ i ] - mans[ j ] ) % MOD print( mans[ 1 ] + ( mans[ 1 ] < 0 ) * MOD ) ```
94,933
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` import sys mod = 10**9 + 7 def solve(): n = int(input()) a = [int(i) for i in input().split()] cnt = [0]*(10**5 + 1) pat = [0]*(10**5 + 1) for ai in a: cnt[ai] += 1 for i in range(1, 10**5 + 1): for j in range(2*i, 10**5 + 1, i): cnt[i] += cnt[j] pat[i] = (pow(2, cnt[i], mod) - 1) for i in range(10**5, 0, -1): for j in range(2*i, 10**5 + 1, i): pat[i] = (pat[i] - pat[j]) % mod ans = pat[1] % mod print(ans) if __name__ == '__main__': solve() ```
94,934
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` #Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue #sys.stdin = open("input.txt", "r") MOD = 10**9+7 sys.setrecursionlimit(1000000) def getMul(x): a = 1 for xi in x: a *= xi return a n = int(input()) a = list(map(int, input().split())) d = {} for ai in a: if ai in d: d[ai] += 1 else: d[ai] = 1 f = [[] for i in range(max(a)+10)] for i in range(1, len(f)): for j in range(i, len(f), i): f[j].append(i) seq = [0 for i in range(max(a)+10)] for ai in d: for fi in f[ai]: seq[fi] += d[ai] for i in range(len(seq)): seq[i] = (pow(2, seq[i], MOD) -1 +MOD) % MOD pf = [[] for i in range(max(a)+10)] pf[0] = None pf[1].append(1) for i in range(2, len(f)): if len(pf[i]) == 0: for j in range(i, len(pf), i): pf[j].append(i) for i in range(1, len(pf)): mul = getMul(pf[i]) if mul == i: if len(pf[i])&1 == 1: pf[i] = -1 else: pf[i] = 1 else: pf[i] = 0 pf[1] = 1 ans = 0 for i in range(1, len(seq)): ans += seq[i]*pf[i] ans = (ans + MOD) % MOD print(ans) ```
94,935
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` # 803F import math import collections def do(): n = int(input()) nums = map(int, input().split(" ")) count = collections.defaultdict(int) for num in nums: for i in range(1, int(math.sqrt(num))+1): cp = num // i if num % i == 0: count[i] += 1 if cp != i and num % cp == 0: count[cp] += 1 maxk = max(count.keys()) freq = {k: (1 << count[k]) - 1 for k in count} for k in sorted(count.keys(), reverse=True): for kk in range(k << 1, maxk+1, k): freq[k] -= freq[kk] if kk in freq else 0 return freq[1] % (10**9 + 7) print(do()) ```
94,936
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Tags: bitmasks, combinatorics, number theory Correct Solution: ``` N = 10**5+5 MOD = 10**9+7 freq = [0 for i in range(N)] # Calculating {power(2,i)%MOD} and storing it at ith pos in p2 arr p2 = [0 for i in range(N)] p2[0] = 1 for i in range(1,N): p2[i] = p2[i-1]*2 p2[i]%=MOD def Calculate_Mobius(N): arr = [1 for i in range(N+1)] prime_count = [0 for i in range(N+1)] mobius_value = [0 for i in range(N+1)] for i in range(2,N+1): if prime_count[i]==0: for j in range(i,N+1,i): prime_count[j]+=1 arr[j] = arr[j] * i for i in range(1, N+1): if arr[i] == i: if (prime_count[i] & 1) == 0: mobius_value[i] = 1 else: mobius_value[i] = -1 else: mobius_value[i] = 0 return mobius_value # Caluclating Mobius values for nos' till 10^5 mobius = Calculate_Mobius(N) n = int(input()) b = [int(i) for i in input().split()] # Storing freq of I/p no.s in array for i in b: freq[i]+=1 ans = 0 for i in range(1,N): # Count no of I/p no's which are divisible by i cnt = 0 for j in range(i,N,i): cnt += freq[j] total_subsequences = p2[cnt] - 1 ans = (ans + (mobius[i] * total_subsequences)%MOD)%MOD # Dealing if ans is -ve due to MOD ans += MOD print(ans%MOD) ```
94,937
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Submitted Solution: ``` N = 10**5+5 MOD = 10**9+7 freq = [0 for i in range(N)] # Calculating {power(2,i)%MOD} and storing it at ith pos in p2 arr p2 = [0 for i in range(N)] p2[0] = 1 for i in range(1,N): p2[i] = p2[i-1]*2 p2[i]%=MOD def Calculate_Mobius(N): arr = [1 for i in range(N+1)] prime_count = [0 for i in range(N+1)] mobius_value = [0 for i in range(N+1)] for i in range(2,N+1): if prime_count[i]==0: for j in range(i,N+1,i): prime_count[j]+=1 arr[j] = arr[j] * i for i in range(1, N+1): if arr[i] == i: if (prime_count[i] & 1) == 0: mobius_value[i] = 1 else: mobius_value[i] = -1 else: mobius_value[i] = 0 return mobius_value # Caluclating Mobius values for nos' till 10^5 mobius = Calculate_Mobius(N) b = [int(i) for i in input().split()] # Storing freq of I/p no.s in array for i in b: freq[i]+=1 ans = 0 for i in range(1,N): # Count no of I/p no's which are divisible by i cnt = 0 for j in range(i,N,i): cnt += freq[j] total_subsequences = p2[cnt] - 1 ans = (ans + (mobius[i] * total_subsequences)%MOD)%MOD # Dealing if ans is -ve due to MOD ans += MOD print(ans%MOD) ``` No
94,938
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Submitted Solution: ``` #Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue #sys.stdin = open("input.txt", "r") MOD = 10**9+7 sys.setrecursionlimit(1000000) n = int(input()) a = list(map(int, input().split())) if a[0] == 1: ans = 1 else: ans = 0 gs = {a[0]: 1} for i in range(1, n): if a[i] == 1: ans = (ans+1) % MOD temp = {} for g in gs: gx = math.gcd(g, a[i]) if gx == 1: ans = (ans+gs[g]) % MOD if gx in gs: if gx in temp: temp[gx] = (temp[gx]+gs[g]) % MOD else: temp[gx] = (gs[gx]+gs[g]) % MOD else: temp[gx] = gs[g] for k in temp: gs[k] = temp[k] if a[i] in gs: gs[a[i]] += 1 else: gs[a[i]] = 1 print(ans) ``` No
94,939
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Submitted Solution: ``` fact=[1] temp=1 MOD=10**9+7 for i in range(1,10**5+5): temp*=i temp%=MOD fact+=[temp] def bino(a,b): up=fact[a] down=pow(fact[b]*fact[a-b],MOD-2,MOD) return (up*down)%MOD def find(A): MOD=10**9+7 dp=[0]*(10**5+2) for x in A: dp[x]+=1 for i in range(2,len(dp)): for j in range(2,len(dp)): if i*j>len(dp)-1: break dp[i]+=dp[i*j] for i in range(2,len(dp)): dp[i]=(pow(2,dp[i],MOD)-1)%MOD for i in range(len(dp)-1,1,-1): for j in range(2,len(dp)): if i*j>=len(dp): break dp[i]-=dp[i*j] dp[i]%=MOD ans=0 for i in range(2,len(dp)): ans+=dp[i] ans%=MOD return (pow(2,len(A),MOD)-ans-1)%MOD print(find(list(map(int,input().strip().split(' '))))) ``` No
94,940
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. Input The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000). Output Print the number of coprime subsequences of a modulo 109 + 7. Examples Input 3 1 2 3 Output 5 Input 4 1 1 1 1 Output 15 Input 7 1 3 5 15 3 105 35 Output 100 Note In the first example coprime subsequences are: 1. 1 2. 1, 2 3. 1, 3 4. 1, 2, 3 5. 2, 3 In the second example all subsequences are coprime. Submitted Solution: ``` # 803F import math import collections def do(): n = int(input()) nums = map(int, input().split(" ")) count = collections.defaultdict(int) for num in nums: for i in range(1, int(math.sqrt(num))+1): cp = num // i if num % i == 0: count[i] += 1 if cp != i and num % cp == 0: count[cp] += 1 maxk = max(count.keys()) freq = {k: (1 << count[k]) - 1 for k in count} for k in sorted(count.keys(), reverse=True): for kk in range(k << 1, maxk+1, k): freq[k] -= freq[kk] if kk in freq else 0 return freq[1] print(do()) ``` No
94,941
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n,k=list(map(int,input().strip().split(' '))) import math L=math.ceil((n-(k+1))/(k)) remain=(n-(k+1))%(k) if (n-(k+1))%(k)==0: remain+=k #print(L,remain,'L,remain') if remain%(k)==1: print(2*(L)+1) else: print(2*(L+1)) if 1==1: if n==2: print(1,2) else: temp=0 end=k+1 for j in range(2,k+1+1): print(1,j) if temp<remain: for p in range(0,L): if p==0: print(j,end+1) end+=1 else: print(end,end+1) end+=1 temp+=1 else: for p in range(0,L-1): if p==0: print(j,end+1) end+=1 else: print(end,end+1) end+=1 ```
94,942
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` inp = [ int(x) for x in input().split() ] n = inp[0] k = inp[1] mainLen = (n-1) // k nodeLeft = (n-1) % k if nodeLeft == 0: print(mainLen*2) elif nodeLeft == 1: print(mainLen*2 + 1) else: print(mainLen*2 + 2) for i in range(1, n): if i <= k: print(str(n) + ' ' + str(i)) else: print(str(i-k) + ' ' + str(i)) ```
94,943
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` import sys def main(): n,k = map(int,sys.stdin.readline().split()) a = n-k if a ==1: print(2) for i in range(k): print(1,i+2) elif a > k+1 : l = ((a-1)//k +1)*2 if (a-1)%k>1: print(l+2) elif (a-1)%k==1: print(l+1) else: print(l) c = 2 for i in range(k): print(1,c) for j in range(l//2-1): print(c,c+1) c+=1 if i<((a-1)%k): print(c,c+1) c+=1 c+=1 else: if a==2: print(3) else: print(4) c =2 for i in range(a-1): print(1,c) print(c, c+1) c+=2 for i in range(c,n+1): print(1,i) main() ```
94,944
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n, k = map(int, input().split()) div = (n - 1) // k rem = (n - 1) % k if rem == 0: print(div * 2) elif rem == 1: print(2 * div + 1) else: print(2 * (div + 1)) j = 2 rest = k - rem while rem > 0: print(1, j) for i in range(div): print(i + j, i + j + 1) j += (div + 1) rem -= 1 while rest > 0: print(1, j) for i in range(div - 1): print(i + j, i + j + 1) j += div rest -= 1 ```
94,945
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` from sys import stdin, stdout from collections import deque def bfs(v): ans = 0 visit[v] = 1 queue = deque() queue.append((v, 0)) while (queue): v, dist = queue.popleft() ans = max(ans, dist) for u in vertices[v]: if not visit[u]: queue.append((u, dist + 1)) visit[u] = 1 return ans n, k = map(int, stdin.readline().split()) challengers = [] ans = [] for i in range(2, k + 2): ans.append((1, i)) challengers.append(i) n = n - k - 1 v = k + 2 for i in range(n // k): update = [] for u in challengers: update.append(v) ans.append((u, v)) v += 1 challengers = update[:] for u in challengers[:n % k]: ans.append((u, v)) v += 1 visit = [0 for i in range(v)] vertices = [[] for i in range(v)] for a, b in ans: vertices[a].append(b) vertices[b].append(a) stdout.write(str(bfs(v - 1)) + '\n') for a, b in ans: stdout.write(str(a) + ' ' + str(b) + '\n') ```
94,946
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n, k = map(int, input().split()) reb = n - 1 our = reb // k if reb % k == 0: eps = 0 elif reb % k == 1: eps = 1 else: eps = 2 print(our * 2 + eps) next = 2 big = reb % k for i in range(big): prev = 1 for j in range(our + 1): print(prev, next) prev = next next += 1 for i in range(k - big): prev = 1 for j in range(our): print(prev, next) prev = next next += 1 ```
94,947
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n,k = map(int,input().split()) n -= 1 val = n//k div = n%k i = 2 if div==0: print(val*2) elif div==1: print(val*2+1) else: print((val+1)*2) for a in range(k): print(1,i) for j in range(val-1): print(i,i+1) i+=1 i+=1 j = i-1 while(div): print(j,i) i+=1 j-=val div -= 1 ```
94,948
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` nodes, exits = [int(x) for x in input().split()] nonExits = nodes - exits nonE = list(range(exits + 1, nodes + 1)) #1 -> exits + 1 :: lopud #exits + 1 -> nodes + 1 :: mitte lopud nonStart = exits + 1 an = [] exitList = [] for i in range(1, exits + 1): exitList.append([i, i, 0]) if nonExits == 1: print(2) for i in range(2, nodes + 1): print(1, i) else: #maxDist = (nonExits + exits - 1) // exits while nonE: for item in exitList: if nonE: it = nonE.pop() an.append((item[1], it)) item[1] = it item[2] += 1 else: break for item in exitList: if item[2] == 0: an.append((item[0], nonStart)) for i in range(1, min(exits, nonExits)): an.append((exitList[0][1], exitList[i][1])) fix = 0 if len(exitList) > 2: if (exitList[2][2] == exitList[1][2] and exitList[2][2] == exitList[0][2]): fix = 1 print(exitList[0][2] + exitList[1][2] + 1 + fix) for i in an: print(i[0], i[1]) ```
94,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` n, k = map(int, input().split()) r = (n-1)//k l = n - 1 x, y, = 1, 2 diam = 2*r if (n-1)%k == 1: diam += 1 elif (n-1)%k >= 2: diam += 2 print(diam) for i in range(k): br = r if i < (n-1)%k: br += 1 x = 1 for j in range(br): print(x, y) x = y y = y + 1 l -= 1 ``` Yes
94,950
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` import math as mt import sys,string input=sys.stdin.readline #print=sys.stdout.write import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,m=M() if((n-1)%m==0): ans=2*((n-1)//m) else: if((n-1)%m>1): ans=2*((n-1)//m)+2 else: ans=2*((n-1)//m)+1 print(ans) w=(n-1)%m x=1 for i in range(m): x+=1 print(1,x) for j in range((n-1)//m-1): print(x,x+1) x+=1 if(w>0): print(x,x+1) x+=1 w-=1 ``` Yes
94,951
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` n,k=map(int,input().split()) print(((n-1)//k)*2+min(2,(n-1)%k)) for i in range(2,n+1): print(i,max(i-k,1)) ``` Yes
94,952
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` import math n,k=map(int,input().split()) sum=math.floor((n-1)/k)*2+min(2,(n-1)%k) print(sum) for i in range(2,n+1): print(i,max(i-k,1)) ``` Yes
94,953
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` nodes, exits = [int(x) for x in input().split()] nonExits = nodes - exits nonE = list(range(exits + 1, nodes + 1)) #1 -> exits + 1 :: lopud #exits + 1 -> nodes + 1 :: mitte lopud nonStart = exits + 1 an = [] exitList = [] for i in range(1, exits + 1): exitList.append([i, i, 0]) if nonExits == 1: print(2) for i in range(2, nodes + 1): print(1, i) else: #maxDist = (nonExits + exits - 1) // exits while nonE: for item in exitList: if nonE: it = nonE.pop() an.append((item[1], it)) item[1] = it item[2] += 1 else: break for item in exitList: if item[2] == 0: an.append((item[0], nonStart)) for i in range(1, min(exits, nonExits)): an.append((exitList[0][1], exitList[i][1])) fix = 0 if len(exitList) > 2: if (exitList[2][2] == exitList[1][2]): fix = 1 print(exitList[0][2] + exitList[1][2] + 1 + fix) for i in an: print(i[0], i[1]) ``` No
94,954
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() n,k = Ri() lis = [i for i in range(k)] ans = [] cur = k totans = 0 while True: tlis = [] while len(lis): if cur == n-1: break # temp = ans.append((lis[-1], cur)) tlis.append(cur) cur+=1 lis.pop() if len(lis) != 0: for i in tlis: ans.append((i, cur)) for i in lis: ans.append((i, cur)) if len(tlis) > 0: totans+=2 totans = totans+(totans-1) else: totans+=1 totans = 2*totans break lis = tlis print(totans) for i in ans: print(i[0]+1, i[1]+1) ``` No
94,955
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` n,k = map(int,input().split()) k -= 2 n-=k sp = False val = 0 if k==0: val = n-1 elif n%2!=0 and k%2==0: sp = True val = (n-k+1)//2 + 1 elif n%2==0 and k%2!=0: val = (n-k+1)//2 + 1 else: val = (n-k)//2+1 print(max(val, n-1)) j = 1 for i in range(n-1): print(j,j+1) j+=1 if sp: for i in range(val,val+k-1): if i==n//2+1: print(i,j+1) j+=1 print(i,j+1) else: print(i,j+1) j+=1 else: for i in range(val,val+k): print(i,j+1) ``` No
94,956
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image> Submitted Solution: ``` import math as mt import sys,string input=sys.stdin.readline #print=sys.stdout.write import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,m=M() if((n-1)%m==0): ans=2*((n-1)//m) else: ans=2*((n-1)//m)+1 print(ans) w=(n-1)%m x=1 for i in range(m): x+=1 print(1,x) for j in range((n-1)//m-1): print(x,x+1) x+=1 if(w>0): print(x,x+1) x+=1 w-=1 ``` No
94,957
Provide tags and a correct Python 3 solution for this coding contest problem. You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle n × m in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters S) and the terminating square (it is marked with a capital Latin letter T). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than k different types of squares (squares of one type can be visited an infinite number of times). Squares marked with S and T have no type, so they are not counted. But S must be visited exactly once — at the very beginning, and T must be visited exactly once — at the very end. Your task is to find the path from the square S to the square T that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types. Input The first input line contains three integers n, m and k (1 ≤ n, m ≤ 50, n·m ≥ 2, 1 ≤ k ≤ 4). Then n lines contain the map. Each line has the length of exactly m characters and consists of lowercase Latin letters and characters S and T. It is guaranteed that the map contains exactly one character S and exactly one character T. Pretest 12 is one of the maximal tests for this problem. Output If there is a path that satisfies the condition, print it as a sequence of letters — the plot types. Otherwise, print "-1" (without quotes). You shouldn't print the character S in the beginning and T in the end. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted. Examples Input 5 3 2 Sba ccc aac ccc abT Output bcccc Input 3 4 1 Sxyy yxxx yyyT Output xxxx Input 1 3 3 TyS Output y Input 1 4 1 SxyT Output -1 Tags: graphs, greedy, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 from itertools import combinations from collections import deque def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) chars = ( ['}' * (m + 2)] + ['}' + ''.join('{' if c == 'S' else '|' if c == 'T' else c for c in input().rstrip()) + '}' for _ in range(n)] + ['}' * (m + 2)] ) cbit = [[1 << (ord(c) - 97) for c in chars[i]] for i in range(n + 2)] si, sj, ti, tj = 0, 0, 0, 0 for i in range(1, n + 1): for j in range(1, m + 1): if chars[i][j] == '{': si, sj = i, j cbit[i][j] = 0 if chars[i][j] == '|': ti, tj = i, j ans = inf = '*' * (n * m) for comb in combinations([1 << i for i in range(26)], r=k): enabled = sum(comb) dp = [[inf] * (m + 2) for _ in range(n + 2)] dp[ti][tj] = '' dq = deque([(ti, tj, '')]) while dq: i, j, s = dq.popleft() if dp[i][j] < s: continue for di, dj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)): if (cbit[di][dj] & enabled) != cbit[di][dj]: continue pre = chars[di][dj] if cbit[di][dj] else '' l = 1 if cbit[di][dj] else 0 if (len(dp[di][dj]) > len(s) + l or len(dp[di][dj]) == len(s) + l and dp[di][dj] > pre + s): dp[di][dj] = pre + s if l: dq.append((di, dj, pre + s)) if len(ans) > len(dp[si][sj]) or len(ans) == len(dp[si][sj]) and ans > dp[si][sj]: ans = dp[si][sj] print(ans if ans != inf else -1) ```
94,958
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` from sys import stdin, stdout n = int(stdin.readline()) s = stdin.readline().strip() cnt = [[0, 0] for i in range(n)] cnt[0][1] = int(s[0]) cnt[0][0] = 1 - int(s[0]) for i in range(1, n): cnt[i][1] += cnt[i - 1][1] + int(s[i]) cnt[i][0] = i + 1 - cnt[i][1] cnt.append([0, 0]) ans = 0 for i in range(n): value = int(s[i]) current = i + ans while current < n: if max(cnt[current][1] - cnt[i - 1][1], cnt[current][0] - cnt[i - 1][0]) != min(cnt[current][1] - cnt[i - 1][1], cnt[current][0] - cnt[i - 1][0]): current += (max(cnt[current][1] - cnt[i - 1][1], cnt[current][0] - cnt[i - 1][0]) - min(cnt[current][1] - cnt[i - 1][1], cnt[current][0] - cnt[i - 1][0])) else: ans = max(ans, current - i + 1) current += 1 stdout.write(str(ans)) ```
94,959
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` n = int(input()); res = [] s = input(); heights = {0 : [-1]}; current = 0 for i in range(n): current += (-1)**int(s[i]) if current not in heights: heights[current] = [i] else: heights[current].append(i) for i in heights.values(): res.append(max(i) - min(i)) print(max(res)) ```
94,960
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` """ Code of Ayush Tiwari Codeforces: servermonk Codechef: ayush572000 """ def solution(): n=int(input()) s=input() cnt1=[0]*(n+1) cnt0=[0]*(n+1) balance=[0] for i in range(n): if s[i]=='1': cnt1[i+1]+=cnt1[i]+1 cnt0[i+1]=cnt0[i] else: cnt1[i+1]=cnt1[i] cnt0[i+1]+=cnt0[i]+1 x=cnt1[i+1]-cnt0[i+1] balance.append(x) d={} ans=0 for i in range(n+1): if d.get(balance[i],-1)==-1: d[balance[i]]=i else: ans=max(ans,i-d[balance[i]]) print(ans) solution() ```
94,961
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` import traceback import math from collections import defaultdict from functools import lru_cache def main(): N = int(input()) nums = input() dp = [0] * N tot = 0 for i in range(N): tot += 1 if nums[i] == '1' else -1 dp[i] = tot # if tot == 0: # return N loc = {} loc[0] = -1 ans = 0 for i in range(N): loc.setdefault(dp[i], i) ans = max(ans, i - loc[dp[i]]) return ans try: ans = main() print(ans) except Exception as e: # print(e) traceback.print_exc() ```
94,962
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` from itertools import accumulate n=int(input()) m={0:-1} a=0 for i,b in enumerate(accumulate(map(lambda c:2*int(c)-1,input()))): x=m.get(b) if x is None: m[b]=i else: a=max(a,i-x) print(a) ```
94,963
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` n=int(input()) l=[int(i) for i in input()] d={} for i in range(n): if l[i]==0: l[i]=-1 else: l[i]=1 from collections import defaultdict d=defaultdict(int) #d[0]=1 sm=0 ans=0 maxi=0 d={} d[0]=-1 for i in range(n): sm+=l[i] # print(sm) if sm in d: maxi=max(maxi,i-d[sm]) if sm not in d: d[sm]=i print(maxi) exit() ans=0 for i in d: c=d[i] ans+=c*(c-1)//2 print(ans) ```
94,964
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` import io,os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n = int(input()) s = [int(x) for x in list(input())] l = [] z = 0 o = 0 d = {} d[0] = -1 for i in range(n): if(s[i] == 0): z+=1 else: o+=1 l.append(z-o) ans = 0 for i in range(n): if(l[i] not in d): d[l[i]] = i else: ans = max(ans, i-d[l[i]]) # print(l) print(ans) ```
94,965
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Tags: dp, implementation Correct Solution: ``` n = int(input()) zo = input() dr = [0] ml = 0 mini = {0: 0} for i in range(n): if zo[i]=='0': dr.append(dr[i]-1) else: dr.append(dr[i]+1) if not(dr[i+1] in mini): mini[dr[i+1]] = i+1 else: ml = max(ml, i+1 - mini[dr[i+1]]) print(ml) ```
94,966
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` n = int(input()) l = [-2] * (n * 2 + 1) l[n], r = -1, 0 for i, c in enumerate(input()): n += {'0': -1, '1': 1}[c] if l[n] == -2: l[n] = i else: i -= l[n] if r < i: r = i print(r) ``` Yes
94,967
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` from collections import defaultdict n = int(input()) s = [int(i) for i in input().strip()] balance = 0 ans = 0 seen = defaultdict(lambda: -2) seen[0] = -1 for j, i in enumerate(s): if i: balance += 1 else: balance -= 1 if seen[balance] == -2: seen[balance] = j ans = max(ans, j - seen[balance]) print(ans) ``` Yes
94,968
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` n=int(input()) T=input() d={0:-1} s=0 mix=0 for i in range(n): if(T[i]=='0'): s+=-1 else : s+=1 if s not in d: d[s]=i else: if(i-d[s])> mix: mix=i-d[s] print(mix) ``` Yes
94,969
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` n = input() s = input() res = 0 ans = 0 dp = {} dp[0] = -1 for i in range(int(n)): if s[i] == '1': res += 1 else: res -= 1 if res not in dp: dp[res] = i else: ans = max(ans, i - dp[res]) print(ans) ``` Yes
94,970
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` n = int(input()) s = str(input()) count0 = s.count('0') count1 = s.count('1') if count0 == 0 or count1 == 0: print('0') elif count0 == count1: print(n) elif count0>count1: print(2*count1) else: print(2*count0) ``` No
94,971
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` ##a = list(map(int, input().split())) ##print(' '.join(map(str, res))) n = int(input()) s = input() ps = [0 for i in range(n+1)] for i in range(0, n): ps[i+1] = ps[i]+(0 if s[i] == '0' else 1) l = 0 r = n//2 while l < r: x = (l+r+1)//2 flag = False for i in range(n-2*x+1): if (ps[i+2*x]-ps[i]) == x: flag = True break if flag: l = x else: r = x-1 print(2*l) ``` No
94,972
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` def ch(s): if s.count('0')==s.count('1'): return True else: return False n=int(input()) s=input() c=0 for i in range(n): for j in range(i+1,n): x=s[i:j] if ch(x): if len(x)>c: c=len(x) print(c) ``` No
94,973
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanced substring of s. Input The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s. Output If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring. Examples Input 8 11010111 Output 4 Input 3 111 Output 0 Note In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible. In the second example it's impossible to find a non-empty balanced substring. Submitted Solution: ``` import sys placeholder = sys.stdin.readline().strip().split(" ") string = sys.stdin.readline().strip().split(" ") """ string = "111" """ num_zeros = 0 num_ones = 0 for x in string: if(x == '0'): num_zeros+=1 elif(x == '1'): num_ones+=1 print(2 * min(num_zeros, num_ones)) ``` No
94,974
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` # http://codeforces.com/contest/899/problem/A n = int(input()) people = [int(x) for x in input().split()] count_2, count_3 = 0, 0 for x in people: if x == 2: count_2 += 1 else: count_3 += 1 if count_2 < count_3: print(count_2 + int((count_3 - count_2)/3)) else: print(count_3) ```
94,975
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` t=(int(input())) l=list(map(int,input().split())) one,two=0,0 for i in l: if i==1: one=one+1 else: two=two+1 if one<=two: print(one) else: print(two+(one-two)//3) ```
94,976
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` n = int(input()) num = list(map(int, input().split())) o = num.count(1) t = num.count(2) if t >= o: out = o t -= o else: out = t o -= t out += int(o / 3) print(out) ```
94,977
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` n = int(input()) A = list(input().split()) c = [A.count("1"), A.count("2")] if c[0] > c[1]: k = c[1] c = [c[0] - c[1], 0] k += c[0] // 3 else: k = c[0] print(k) ```
94,978
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Fri Apr 3 01:33:24 2020 @author: Designer """ even=0 odd=0 a=int(input('')) b=str(input('').strip()) for i in range(0,len(b),2): if b[i] == '2': even=even+1 else: odd=odd+1 if odd == 0: print(0) elif even>odd: print(odd) else: c=odd-even n=c//3 print(even+n) ```
94,979
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) cnt = min(a.count(1), a.count(2)) ans = cnt + max(0, (a.count(1) - cnt) // 3) print(ans) ```
94,980
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` input() data = list(map(int, input().split())) n1 = data.count(1) n2 = len(data) - n1 print(min(n1, n2) + (n1 - min(n1, n2)) // 3) ```
94,981
Provide tags and a correct Python 3 solution for this coding contest problem. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Tags: constructive algorithms, greedy, math Correct Solution: ``` n = int(input()) l = [int(i) for i in input().split(" ")] one = l.count(1) two = n - one result = 0 if two >= one: result = one else: result += two one = one - two result += int(one/3) print(result) ```
94,982
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` n=int(input()) stu = input().split() lis = list(map(int,stu)) ones = lis.count(1) twos = lis.count(2) if twos<=ones: ans = twos + (ones-twos)//3 else: ans = ones print(ans) ``` Yes
94,983
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) x=a.count(1) y=n-x ans=min(x,y) x-=ans ans+=x//3 print(ans) ``` Yes
94,984
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` import sys,collections sys.setrecursionlimit(10**7) def Is(): return [int(x) for x in sys.stdin.readline().split()] def Ss(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def S(): return input() n = I() a = Is() two = a.count(2) one = a.count(1) twoOne = min(one,two) print(twoOne + (one-twoOne)//3) ``` Yes
94,985
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) one=a.count(1) two=a.count(2) if one>two: print(two+(one-two)//3) else: print(one) ``` Yes
94,986
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) if 1 not in a: print("0") elif 2 not in a: print(n//3) else: x=a.count(1) y=a.count(2) if y>=x: print(x) else: print(x + ((x-y)//3)) ``` No
94,987
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` n=int(input()) stu = input().split() lis = list(map(int,stu)) ones = lis.count(1) twos = lis.count(2) if twos<=ones: ans = twos + (ones-twos)//3 else: ans = ones + ((twos-ones)*2)//6 print(ans) ``` No
94,988
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` a=int(input()) l=list(map(int,input().split())) o=l.count(1) t=a-o if t<=o: print(t+(o-t)//3) else: print(o//3) ``` No
94,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. Input The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i. Output Print the maximum number of teams of three people the coach can form. Examples Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 Note In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: * The first group (of two people) and the seventh group (of one person), * The second group (of two people) and the sixth group (of one person), * The third group (of two people) and the fourth group (of one person). Submitted Solution: ``` n=int(input()) m=list(map(int,input().split())) if (len(set(m)))==1 and list(set(m))!=[1] : print(0) else: if list(set(m))==[1]: print(n//3) else: print(min(n-(m.count(2)),(m.count(2)))) ``` No
94,990
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` def displeasure(wal_arr): wal_arr = sorted(wal_arr) highest_ind = -1 ret_arr = [-1] * len(wal_arr) for wal in wal_arr: if wal[1] < highest_ind: ret_arr[wal[1]] = highest_ind - wal[1] - 1 highest_ind = max(highest_ind, wal[1]) return ret_arr num = input() walrus_arr = input().split(" ") walrus_arr = [(int(age), ind) for ind, age in enumerate(walrus_arr)] for wal in displeasure(walrus_arr): print(str(wal) + " ") ```
94,991
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` n = int(input()) A = list(map(int,input().split())) B = [0]*len(A) # список ответов C = [[0]*3 for i in range(len(A))] # хранить мин элементы, индекс текущего и предыдущего минимума B[-1] = -1 C[-1][0] = A[-1] C[-1][1] = len(A)-1 C[-1][2] = len(A) # за границы массива for i in range(len(A)-2,-1,-1): # нужно записывать в список B if A[i] < C[i+1][0]: # то есть слева морж мороже и конфликта нет B[i] = -1 C[i][0] = A[i] C[i][1] = i C[i][2] = C[i+1][1] elif A[i] == C[i+1][0]: B[i] = -1 C[i][0] = A[i] C[i][1] = C[i+1][1] C[i][2] = C[i + 1][2] else: # то есть где-то справа точно есть морж моложе и есть конфликт, который нужно посчитать C[i][0] = C[i+1][0] # т.к. это не новый минимум C[i][1] = C[i + 1][1] C[i][2] = C[i + 1][2] k = 0 m = i while m+1 < len(A) and A[i] > C[C[m+1][1]][0]: k += C[m+1][1] - m m = C[m+1][1] k -= 1 B[i] = k for i in range(len(B)): # инструкция на вывод ответа print(B[i],end=' ') ```
94,992
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` n = int(input()) a = list(map(int,input().split(' '))) ans = [0]*(n) def bsearch(i,l,h): pos = -1 while(h>=l): mid = (l+h)//2 if a[mid]<a[i]: pos = mid l = mid+1 else: h = mid-1 if pos!=-1: return pos-i-1 else: return -1 for i in range(n-1,-1,-1): ans[i] = bsearch(i,i+1,n-1) if i!=n-1: a[i] = min(a[i+1],a[i]) print(' '.join(map(str,ans))) ```
94,993
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures 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(): l1=[] x=l[len(l)-1] l1.append(x) d={} d[x]=len(l)-1 for i in range(len(l)-1,-1,-1): if x>l[i]: x=l[i] d[x]=i l1.append(x) else: l1.append(l1[-1]) ans=[] l1.reverse() #print(l,l1) for i in range(len(l)): if l1[i]<l[i]: pos=bisect.bisect_left(l1,l[i]) #print(l[i],pos) ans.append(d[l1[pos-1]]-i-1) else: ans.append(-1) return ans for _ in range(t): n=int(input()) #n=int(input()) #n,m,k,p=(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() #p=input() l=list(map(float,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()) ```
94,994
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` n = int(input()) from bisect import bisect_left as br a = [int(x) for x in input().split()] mn = [10 ** 10 for i in range(n)] mn[-1] = a[-1] for i in range(n - 2, -1 , -1): mn[i] = min(mn[i + 1], a[i]) ans = [0] * n for i in range(n): pos = br(mn, a[i]) #print(pos) if a[pos - 1] < a[i]: ans[i] = max(-1, pos - 1- i - 1) else: ans[i] = -1 print(*ans) ```
94,995
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` n=int(input()) x=[int(q) for q in input().split()] l=[0]*n def search(i,l,h): pos=-1 while(h>=l): mid=(l+h)//2 if x[mid]<x[i]: pos=mid l=mid+1 else: h=mid-1 if pos!=-1: return pos-i-1 else: return -1 for i in range(n-1,-1,-1): l[i]=search(i,i+1,n-1) if i!=n-1: x[i]=min(x[i+1],x[i]) print(" ".join(map(str,l))) ```
94,996
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` n = int(input()) import bisect arr = list(map(int,input().strip().split()))[:n] mins = [0]*n mins[n-1] = arr[-1] for i in range(n-2,-1,-1): mins[i] = min(mins[i+1],arr[i]) ans = [] for i in range(n-1): if arr[i] <= mins[i+1]: ans.append(-1) else: ind = bisect.bisect_right(mins,arr[i]-1) ans.append(ind-i-2) ans.append(-1) for num in ans: print(num,end=" ") ```
94,997
Provide tags and a correct Python 3 solution for this coding contest problem. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Tags: binary search, data structures Correct Solution: ``` from bisect import * n = int(input()) a = list(map(int, input().split())) b = [0] * n for i in range(n - 1, -1, -1): b[i] = bisect_left(a, a[i], i + 1, n) - i - 2 a[i] = min(a[i + 1], a[i]) if i != n - 1 else a[i] print (*b) ```
94,998
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Submitted Solution: ``` def f(u, low, high): poss = -1 while high >= low: mid = (low + high) // 2 if a[mid] < a[u]: poss = mid low = mid + 1 else: high = mid - 1 return poss - u - 1 if poss != -1 else -1 n = int(input()) a = list(map(int, input().split())) ans = [0] * n for i in range(n - 1, -1, -1): ans[i] = f(i, i + 1, n - 1) if i != n - 1: a[i] = min(a[i + 1], a[i]) print (' '.join(map(str, ans))) ``` Yes
94,999