text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Tags: implementation Correct Solution: ``` from math import * #from bisect import * #from collections import * #from random import * #from decimal import *""" #from heapq import * #from random import * import sys input=sys.stdin.readline #sys.setrecursionlimit(3*(10**5)) global flag def inp(): return int(input()) def st(): return input().rstrip('\n') def lis(): return list(map(int,input().split())) def ma(): return map(int,input().split()) t=1 global li li=[] def rec(st,tu): global li if(tu>10): return if(st): li.append(int(st)) rec(st+'4',tu+1) rec(st+'7',tu+1) rec('',0) while(t): t-=1 l,r=ma() li.sort() co=0 for i in li: if(int(i)<l): continue need=min(int(i)-l+1,r-l+1) #print(need,l,i) l+=need co+=need*int(i) if(l>r): break print(co) ```
91,800
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Tags: implementation Correct Solution: ``` MAX = 10 ** 10 def doit(cur): if cur > MAX: return if cur <= MAX: a.append(cur) doit(cur * 10 + 4) doit(cur * 10 + 7) a = [] doit(0) a.sort() ret = 0 left, right = map(int, input().split()) for i in range(len(a) - 1): l = max(left, a[i] + 1) r = min(right, a[i + 1]) ret += max(r - l + 1, 0) * a[i + 1] print(ret) ```
91,801
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Tags: implementation Correct Solution: ``` def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) # If mid element is greater than # k update leftGreater and r if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) l,r=map(int,input().split()) e=[4,7] t=2 c=0 while(e[-1]<=1000000000): te=len(e) c+=1 for i in range(t): e.append(4*pow(10,c)+e[te-t+i]) for i in range(t): e.append(7*pow(10,c)+e[te-t+i]) t*=2 ind=countGreater(e,len(e),l) s=l ind=len(e)-ind end=min(r,e[ind]) mul=e[ind] #print(mul) ans=0 ty=1 while(True): #print(s,end,mul) ans+=(end-s+1)*mul if end==r: break s=end+1 end=min(r,e[ind+ty]) mul=e[ind+ty] ty+=1 #print(ans) print(ans) ```
91,802
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Tags: implementation Correct Solution: ``` l,r = [int(x) for x in input().strip().split()] def next(n,k): s = n n = int(n) if int("4"*k)>=n: return "4"*k elif int("7"*k)<n: return "4"*(k+1) elif 4<int(s[0])<7: return "7"+"4"*(k-1) if not s[1:]=="": a = next(s[1:],k-1) if s[0]=="4": if len(str(a))==k: return "7"+a[1:] else: return "4"+a else: return "7"+a else: return "7" last = int(next(str(l),len(str(l)))) tot = 0 count = l while count<=r: # print(count,tot,last) tot+=last*(min(last,r)-count+1) count = last+1 b = str(last+1) last=int(next(b,len(b))) print(tot) # print(next("1000000000",len("1000000000"))) ```
91,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` pre = [] prev = [''] for i in range(1, 11): cur = [s + '4' for s in prev] + [s + '7' for s in prev] pre.extend(cur) prev = cur l = sorted(map(int, pre)) x, y = map(int, input().split()) res = 0 for i in l: if i<x: continue res+=i*(min(i,y)-x+1) x=i+1 if x>y: break print(res) ``` Yes
91,804
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` l, r = map(int, input().split()) lst = [] def rec(n): lst.append(n) if n > 10 *r: return rec(n*10+4) rec(n*10+7) return rec(0) lst.sort() s = 0 s2 = 0 for i in range(len(lst)): s += lst[i] * (min(lst[i], r) - min(lst[i-1], r)) s2 += lst[i] * (min(lst[i], l-1) - min(lst[i-1], l-1)) print(s-s2) ``` Yes
91,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` def getLuckyNumber(digit , arr): temp = list() for i in arr: temp.append('4' + i) temp.append('7' + i) return temp def digitCount(number): digits = 1 while True: digits += 1 number = number // 10 if number == 0: break return getLuckyList(digits) def getLuckyList(digitCount): temp = [''] arr = list() for i in range(1 , digitCount + 1): temp = getLuckyNumber(i , temp) luck = list(map(int , temp)) arr += luck arr.sort() return arr def nextLuckyNumber(x , arr): for j in arr: if j >= x: return j if __name__ == "__main__": n = list(map(int , input().rstrip().split())) l = n[0] r = n[1] arr = digitCount(r) total = 0 prev = 0 i = l while i <= r: if i > prev: prev = nextLuckyNumber(i , arr) #print (prev , i) total += prev i += 1 else: if prev <= r: total += (prev - i + 1) * prev else: total += (r - i + 1) * prev i = prev + 1 print (total) ``` Yes
91,806
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` x, y = map(int,input().split()) a=list() a = [4, 7] l = 0 mid = -1 k = len(list(str(y))) while l<k: for m in range(mid+1,len(a)): a.append(str(a[m])+"4") a.append(str(a[m])+"7") l+=1 suma = 0 for m in range(len(a)): if x<= int(a[m]) and y <= int(a[m]) and x <= y: suma+=int(a[m])*(y - x+1) break elif x<=int(a[m]) and y > int(a[m]): suma+=int(a[m])*(int(a[m]) - x+1) x = int(a[m])+1 print(suma) ``` Yes
91,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` maxn=1024 luck=[0]*maxn luck[1]=4 luck[2]=7 def return_sum(n): if n==0: return 0 ans=0 for i in range(maxn): if luck[i]<n: ans+=luck[i]*(luck[i]-luck[i-1]) else: ans+=luck[i]*(n-luck[i-1]) break return ans l,r=map(int,input().split()) x=3 for i in range(1,maxn//2): luck[x]=luck[i]*10+4 x+=1 if x==maxn//2: break luck[x]=luck[i]*10+7 x+=1 print(return_sum(r)-return_sum(l-1)) ``` No
91,808
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` l,r = map(int,input().split(' ')) a = set() for i in range(1, 11): for j in range(2**i): c = j cnt = 0 t = 0 while c or cnt < i: if c&1: t = t*10+7 else: t = t*10+4 cnt += 1 c //= 2 a.add(t) a = sorted(list(a)) print(max(a)) ans = 0 for j in range(len(a)): i = a[j] if l <= i and r > i: ans += (i - l + 1) * i l = i + 1 elif l <= i and r <= i: ans += (r - l + 1) * i break print(ans) ``` No
91,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` l,r=map(int,(input().split())) lucky=[4,7] if l==1000000000 and r==1000000000: print(4444444444) else: for i in range(1,10): for j in lucky[pow(2,i)-2:pow(2,i+1)+1]: lucky.append(4*pow(10,i) + j) lucky.append(7*pow(10,i)+ j) lucky.sort() add=0 for i in lucky: if i<l: lucky.pop(0) for i in range(l,r+1): if i<=lucky[0]: add=add+lucky[0] else: lucky.pop(0) add=add+lucky[0] print(add) ``` No
91,810
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Submitted Solution: ``` from itertools import product x = ['4','7'] lucky_nums = [4,7] for i in range(2,11): for p in product(x,repeat=i): lucky_nums.append(int("".join(p))) n = len(lucky_nums) l,r = map(int,input().split()) li = -1 ri = -1 for i in range(n): if li==-1 and lucky_nums[i] >= l: li = i if lucky_nums[i] <= r: ri = i prev = l ans = 0 for i in range(li,ri+1): ans += (lucky_nums[i]-prev+1)*lucky_nums[i] prev = lucky_nums[i]+1 print(ans) ``` No
91,811
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` n,k=map(int,input().split()) b=list(map(int,input().split())) a=[];dic={} for i in b: try: if dic[i]: dic[i]+=1 except KeyError: dic[i]=1 a.append(i) a.sort() i=0;j=len(a)-1 while(1): frst=a[i];last=a[j] if frst==last: break fcost=dic[frst];lcost=dic[last] fnxt=a[i+1];lnxt=a[j-1] fnxtcost=fnxt-frst;lnxtcost=last-lnxt ftotal=fcost*fnxtcost;ltotal=lcost*lnxtcost if fcost<=lcost: if ftotal<=k: i+=1;k-=ftotal;dic[fnxt]+=fcost;dic[frst]=0 else: temp=k//fcost frst+=temp; k-=(k*temp) break else: if ltotal<=k: j-=1;k-=ltotal;dic[lnxt]+=lcost;dic[last]=0 else: temp=k//lcost k-=(k*temp) last-=temp break print(last-frst) ```
91,812
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers 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 -------------------- import bisect n,k=map(int,input().split()) vals=list(map(int,input().split())) vals.sort() a1=[] a2=[] if n%2==1: moves=0 for s in range(n//2): moves+=abs(vals[s+1]-vals[s])*(s+1) moves+=abs(vals[-1-(s+1)]-vals[-1-s])*(s+1) a1.append(moves) a2.append(abs(vals[s+1]-vals[-1-(s+1)])) else: moves=0 for s in range(n//2 -1): moves+=abs(vals[s+1]-vals[s])*(s+1) moves+=abs(vals[-1-(s+1)]-vals[-1-s])*(s+1) a1.append(moves) a2.append(abs(vals[s+1]-vals[-1-(s+1)])) moves+=abs(vals[n//2 -1]-vals[n//2])*(n//2) a1.append(moves) a2.append(0) ind=bisect.bisect_left(a1,k) if k<a1[0]: print(abs(vals[0]-vals[-1])-k) elif k>=a1[-1]: print(0) else: if k==a1[ind]: print(a2[ind]) elif k<a1[ind]: print(a2[ind-1]-(k-a1[ind-1])//(ind+1)) ```
91,813
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` import sys input=sys.stdin.readline import collections from collections import defaultdict n,k=map(int,input().split()) l=[int(i) for i in input().split()] l.sort() freq=defaultdict(list) for i in l: if i not in freq: freq[i].append(1) else: freq[i][0]+=1 l=list(set(l)) l.sort() #print(freq,l) count=0 beg=0 last=(len(l)-1) diff =l[last]-l[beg] while count<k and diff>0: if freq[l[beg]]<freq[l[last]]: if (count+freq[l[beg]][0])<=k and diff>=0: diff-=min((k-count)//freq[l[beg]][0],(l[beg+1]-l[beg])) count+=min(k-count,freq[l[beg]][0]*(l[beg+1]-l[beg])) freq[l[beg+1]][0]+=freq[l[beg]][0] beg+=1 #print(freq,diff,count,beg) else: count=k else: if (count+freq[l[last]][0])<=k and diff>=0: diff-=min((k-count)//freq[l[last]][0],(l[last]-l[last-1])) count+=min(k-count,freq[l[last]][0]*(l[last]-l[last-1])) #print(freq[l[last-1]]) freq[l[last-1]][0]+=freq[l[last]][0] #print(freq[l[last-1]]) last-=1 #print(freq,diff,count,last) else: count=k print(diff) ```
91,814
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` from sys import stdin input = iter(stdin.buffer.read().decode().splitlines()).__next__ n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() left = 1 right = 1 while 1: if left*(a[left]-a[left-1]) <= k: k -= left*(a[left]-a[left-1]) left += 1 else: print(a[n-right]-a[left-1]-int(k/left)) exit() if left+right > n: print(0) exit() if right*(a[n-right]-a[n-1-right]) <= k: k -= right*(a[n-right]-a[n-1-right]) right += 1 else: print(a[n-right]-a[left-1]-int(k/right)) exit() if left+right > n: print(0) exit() ```
91,815
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` n,k=map(int,input().strip().split()) a =list(map(int,input().strip().split())) from collections import deque, Counter temp = Counter(a) a = deque(sorted(map(lambda x: [x,temp[x]], temp))) # print(a) while( (k>=a[0][1] or k>=a[-1][1] ) and len(a)>1): # forward cf,f,smf = a[0][1], a[0][0], a[1][0] cr,r,smr = a[-1][1], a[-1][0], a[-2][0] if(cf < cr): # front should be removed temp = cf*(smf-f) if(temp<=k): k-=temp a.popleft() a[0][1]+=cf else: factor=k//cf temp1 = factor*cf k-=temp1 a[0][0]=f+factor else: # back should be removed temp = cr*(r-smr) if(temp<=k): k-=temp a.pop() a[-1][1]+=cr else: factor=k//cr temp1 = factor*cr k-=temp1 a[-1][0]=r-factor print(max(a)[0]-min(a)[0]) ```
91,816
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` # encoding: utf-8 from sys import stdin n, k = [int(i) for i in stdin.readline().strip().split()] a = [int(i) for i in stdin.readline().strip().split()] a.sort() i = 0 j = n - 1 a_min = a[i] a_max = a[j] while i < j: if i + 1 <= n - j: required_steps = (a[i + 1] - a[i]) * (i + 1) if required_steps > k: a_min += k // (i + 1) break else: i += 1 k -= required_steps a_min = a[i] else: required_steps = (a[j] - a[j - 1]) * (n - j) if required_steps > k: a_max -= k // (n - j) break else: j -= 1 k -= required_steps a_max = a[j] print(a_max - a_min) ```
91,817
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` import sys import math n,k=map(int,input().split()) A=[int(i) for i in input().split()] A.sort() l=0 r=n-1 while(l<r and k): temp=((A[l+1]-A[l])*(l+1)+(A[r]-A[r-1])*(n-r)) if(k>=temp): k-=temp l+=1 r-=1 else: ans=A[r]-A[l]-(k//(l+1)) print(ans) sys.exit(0) print(0) ```
91,818
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Tags: binary search, constructive algorithms, greedy, sortings, ternary search, two pointers Correct Solution: ``` import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int,minp().split()) def solve(): n, k = mints() a = list(mints()) a.sort() b = [] c = [] i = 0 while i < n: j = i + 1 while j < n and a[j] == a[i]: j += 1 b.append(a[i]) c.append(j-i) i = j l = 0 r = len(b) - 1 while l < r and k > 0: if c[l] < c[r]: x = min(b[l] + k // c[l], b[l+1]) k -= (x - b[l]) * c[l] if x == b[l+1]: c[l+1] += c[l] l += 1 else: b[l] = x break else: x = max(b[r] - k // c[r], b[r-1]) k -= (b[r] - x) * c[r] if x == b[r-1]: c[r-1] += c[r] r -= 1 else: b[r] = x break print(b[r]-b[l]) solve() ```
91,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` n,k=map(int,input().split()) li=list(map(int,input().split())) d={} l=[] for i in li: try: d[i]+=1 except KeyError: d[i]=1 l.append(i) l.sort() z=1 a=0 b=len(l)-1 while k>0: if a==b: z=0 break if d[l[a]]>d[l[b]]: s=d[l[b]]*(l[b]-l[b-1]) if s<=k: k-=s d[l[b-1]]+=d[l[b]] b-=1 else: b1=k//d[l[b]] z=2 break else: s=d[l[a]]*(l[a+1]-l[a]) if s<=k: k-=s d[l[a+1]]+=d[l[a]] a+=1 else: a1=k//d[l[a]] z=3 break if z==0: print(0) elif z==1: print(l[b]-l[a]) elif z==2: print(l[b]-l[a]-b1) else: print(l[b]-l[a]-a1) ``` Yes
91,820
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` n,k=map(int,input().split()) l=list(map(int,input().split())) l.sort() i,j=0,n-1 cnt0,cnt1=1,1 left,right=l[0],l[-1] while(i<j): if(cnt0<=cnt1): x=l[i+1]-l[i] if (cnt0*x)<=k: k-=cnt0*x cnt0+=1 i+=1 left=l[i] else: num=k//(cnt0) left=l[i]+num break else: x=l[j]-l[j-1] if(cnt1*x)<=k: k-=cnt1*x cnt1+=1 j-=1 right=l[j] else: num=k//cnt1 right=l[j]-num break print(right-left) ``` Yes
91,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` import sys from bisect import bisect_left,bisect_right input=sys.stdin.readline n,k=map(int,input().split()) a=list(map(int,input().split())) a.sort() i=0;j=n-1 res=a[j]-a[i] while res>0: if i==j-1: used=(a[i+1]-a[i])*(i+1) else: used=(a[i+1]-a[i]+a[j]-a[j-1])*(i+1) if used>=k: res-=k//(i+1) break k-=used if i==j-1: res=0 break res=a[j-1]-a[i+1] j-=1;i+=1 print(res) ``` Yes
91,822
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` n, k = [int(i) for i in input().split(' ')] a = sorted([int(i) for i in input().split(' ')]) if n == 1: print(0) exit() tot = 0 i, j = 1, n-2 while j - i>=-1: do = i>(n-j-1) last = tot tot += i*(a[i]-a[i-1]) if not do else (n - j - 1)*(a[j+1] - a[j]) if tot >= k: if do: a[-1] -= (k - last)//(n-j-1) else: a[0] += (k - last)//i break if do: a[-1] = a[j] j-=1 else: a[0] = a[i] i+=1 print(a[-1] - a[0]) ``` Yes
91,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` from math import * n,k = map(int,input().split()) l = list(map(int,input().split())) d = dict() for i in l: if i not in d: d[i] = 1 else: d[i] += 1 l = list(set(l)) l.sort() n1 = len(l) i = 0 cs = d[l[0]] cl = d[l[-1]] if(n1 == 1): print(0) else: #print(l) while(k > 0 and i < n1//2): #print(k) diff = l[i+1] - l[i] diff = diff*cs #print(diff) if(diff > k): l[i] += k//cs print(l[n1-1-i] - l[i]) break else: k -= diff cs += d[l[i+1]] diff = l[n1-1-i] - l[n1-2-i] diff = diff *cl #print(diff) if(diff > k): l[n1-1-i] -= k//cl print(l[n1-1-i] - l[i+1]) break else: k -= diff cl += d[l[n1-2-i]] i += 1 else: print(0) ``` No
91,824
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` n,k=map(int, input().split(' ')) a=[] for i in input().split(): a.append(int(i)) a=sorted(a) rez=0 for i in range(k): if a[-1]-a[0]>1: a[0]+=1 a=sorted(a) rez=a[-1]-a[0]-1 else: rez=0 break print(rez) ``` No
91,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` def main(): n,k=readIntArr() a=readIntArr() a.sort() p=a.copy() for i in range(1,n): p[i]+=p[i-1] def getSum(l,r): if l==0: return p[r] else: return p[r]-p[l-1] def raiseLowerLimit(lowerLimit): # returns the number of steps required i=-1 b=n while b>0: while i+b<n and a[i+b]<lowerLimit: i+=b b//=2 if i==-1: return 0 return lowerLimit*(i+1)-getSum(0,i) def decreaseUpperLimit(upperLimit): # returns the number of steps required r=n b=n while b>0: while r-b>=0 and a[r-b]>upperLimit: r-=b b//=2 if r==n: return 0 return getSum(r,n-1)-upperLimit*(n-r) def findMinDiff(lower): # return the minimum difference given lower kLeft=k-raiseLowerLimit(lower) if kLeft<0: return inf b=k optimalUpper=a[n-1] if lower>optimalUpper: return 0 while b>0: while optimalUpper-b>=lower and decreaseUpperLimit(optimalUpper-b)<=kLeft: optimalUpper-=b b//=2 # print('lower:{} kLeft:{}'.format(lower,kLeft)) return optimalUpper-lower optimalLower=a[0] b=k while b>0: while findMinDiff(optimalLower+b)<findMinDiff(optimalLower): optimalLower+=b b//=2 ans=findMinDiff(optimalLower) print(ans) # print(findMinDiff(1)) # print('optimal lower:{}'.format(optimalLower)) # for l in range(a[0],a[n-1]+1): # print('lower:{} minDiff:{}'.format(l,findMinDiff(l))) # print() # print('decreaseUpper:{}'.format(decreaseUpperLimit(4))) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m]) dv=defaultVal;da=dimensionArr if len(da)==1:return [dv for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(x,y): print('? {} {}'.format(x,y)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 for _abc in range(1): main() ``` No
91,826
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Input The first line contains two integers n and k (2 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{9}). Output Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times. Examples Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 Note In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2. In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations. Submitted Solution: ``` n,m=map(int,input().split()) l=list(map(int,input().split())) i=1 s=sum(l) while (i<=m)and(l[0]!=l[n-1]): l.sort() a=l[n-1] b=l[0] v=s/n h1=a-v h2=v-b if h1>=h2: l[n-1]-=1 else : l[0]+=1 i=i+1 l.sort() print(l[n-1]-l[0]) ``` No
91,827
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` MOD = 998244353 def power(x,y): res=1 while(y>0): if(y&1): res = x*res%MOD y = y >>1 x = x*x%MOD return res n = int(input()) prob = input().split() p = power(100,n) q = 1 for i in range(0,n-1): q = q*(int(prob[i]))%MOD p = (p + q*(power(100,n-i-1))%MOD)%MOD q = q*(int(prob[n-1]))%MOD print(p*(power(q,MOD-2))%MOD) ```
91,828
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` #q = int(input()) #x, y = map(int,input().split(' ')) #print (' '.join(list(map(str, s)))) def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m m = 998244353 n = int(input()) p = list(map(int,input().split(' '))) up = 0 low = 1 for i in range(n): up = up + low up = up * 100 % m low = low * p[i] % m print (up*modinv(low,m)%m) ```
91,829
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` def main(): m = 998244353 n = int(input()) pp = map(int,input().split()) probb = 100 num = 0 for i,p in enumerate(pp,1): probu = ((100-p) * probb) % m probb = (p * probb) % m num = (num*100 + i*probu) % m num = (num + n*probb) % m print(( num * pow(probb, m-2, m) ) % m ) if __name__ == "__main__": main() ```
91,830
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` input();p,f=998244353,0 for i in map(int,input().split()):f=100*(f+1)*pow(i,p-2,p)%p print(f) ```
91,831
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` n=int(input()) x=list(map(int,input().split())) s,dp,mod=0,1,998244353 for i in range(n): if i>0: s=(s*100)%mod s=(s+(100-x[i])*dp*(i+1))%mod if i==n-1: s=(s+x[i]*dp*(i+1))%mod dp=(dp*x[i])%mod ans=(s*pow(dp,mod-2,mod))%mod print(ans) ```
91,832
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` N = int(input()) P = list(map(int, input().split())) mod = 998244353 p = 0 q = 1 for i in range(N): p, q = (100 * (p+q)) % mod, (P[i] * q) % mod print((p * pow(q, mod-2, mod))%mod) ```
91,833
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` M = 998244353 def gcd(a, b): if (a == 0): return 0, 1 x, y = gcd(b % a, a) return y - (b // a) * x, x k = input() probs = list(map(int, input().split(' '))) num, denum = 0, 1 for p in probs: num = (num + denum) * 100 % M denum = denum * p % M inv, _ = gcd(denum, M) print(num * inv % M) ```
91,834
Provide tags and a correct Python 3 solution for this coding contest problem. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Tags: data structures, probabilities Correct Solution: ``` import sys readline = sys.stdin.readline from itertools import accumulate from collections import Counter from bisect import bisect as br, bisect_left as bl class PMS: #1-indexed def __init__(self, A, B, issum = False): #Aに初期状態の要素をすべて入れる,Bは値域のリスト self.X, self.comp = self.compress(B) self.size = len(self.X) self.tree = [0] * (self.size + 1) self.p = 2**(self.size.bit_length() - 1) self.dep = self.size.bit_length() CA = Counter(A) S = [0] + list(accumulate([CA[self.X[i]] for i in range(self.size)])) for i in range(1, 1+self.size): self.tree[i] = S[i] - S[i - (i&-i)] if issum: self.sumtree = [0] * (self.size + 1) Ssum = [0] + list(accumulate([CA[self.X[i]]*self.X[i] for i in range(self.size)])) for i in range(1, 1+self.size): self.sumtree[i] = Ssum[i] - Ssum[i - (i&-i)] def compress(self, L): #座圧 L2 = list(set(L)) L2.sort() C = {v : k for k, v in enumerate(L2, 1)} # 1-indexed return L2, C def leng(self): #今入っている個数を取得 return self.count(self.X[-1]) def count(self, v): #v(Bの元)以下の個数を取得 i = self.comp[v] s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def less(self, v): #v(Bの元である必要はない)未満の個数を取得 i = bl(self.X, v) s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def leq(self, v): #v(Bの元である必要はない)以下の個数を取得 i = br(self.X, v) s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, v, x): #vをx個入れる,負のxで取り出す,iの個数以上取り出すとエラーを出さずにバグる i = self.comp[v] while i <= self.size: self.tree[i] += x i += i & -i def get(self, i): # i番目の値を取得 if i <= 0: return -1 s = 0 k = self.p for _ in range(self.dep): if s + k <= self.size and self.tree[s+k] < i: s += k i -= self.tree[s] k //= 2 return self.X[s] def gets(self, v): #累積和がv以下となる最大のindexを返す v1 = v s = 0 k = self.p for _ in range(self.dep): if s + k <= self.size and self.sumtree[s+k] < v: s += k v -= self.sumtree[s] k //= 2 if s == self.size: return self.leng() return self.count(self.X[s]) + (v1 - self.countsum(self.X[s]))//self.X[s] def addsum(self, i, x): #sumを扱いたいときにaddの代わりに使う self.add(i, x) x *= i i = self.comp[i] while i <= self.size: self.sumtree[i] += x i += i & -i def countsum(self, v): #v(Bの元)以下のsumを取得 i = self.comp[v] s = 0 while i > 0: s += self.sumtree[i] i -= i & -i return s def getsum(self, i): #i番目までのsumを取得 x = self.get(i) return self.countsum(x) - x*(self.count(x) - i) N, Q = map(int, readline().split()) P = list(map(int, readline().split())) MOD = 998244353 T = [100*pow(pi, MOD-2, MOD)%MOD for pi in P] AT = [None]*N AT[0] = T[0] for i in range(1, N): AT[i] = (AT[i-1]+1)*T[i]%MOD AM = [None]*N AMi = [None]*N AM[0] = T[0] for i in range(1, N): AM[i] = AM[i-1]*T[i]%MOD AMi[N-1] = pow(AM[N-1], MOD-2, MOD) for i in range(N-2, -1, -1): AMi[i] = AMi[i+1]*T[i+1]%MOD AT += [0] AM += [1] AMi += [1] Ans = [None]*Q kk = set([0, N]) PM = PMS([0, N], list(range(N+1))) ans = AT[N-1] for qu in range(Q): f = int(readline()) - 1 if f not in kk: kk.add(f) PM.add(f, 1) fidx = PM.count(f) fm = PM.get(fidx-1) fp = PM.get(fidx+1) am = (AT[f-1] - AM[f-1]*AMi[fm-1]*AT[fm-1])%MOD ap = (AT[fp-1] - AM[fp-1]*AMi[f-1]*AT[f-1])%MOD aa = (AT[fp-1] - AM[fp-1]*AMi[fm-1]*AT[fm-1])%MOD ans = (ans - aa + am + ap)%MOD else: kk.remove(f) fidx = PM.count(f) fm = PM.get(fidx-1) fp = PM.get(fidx+1) PM.add(f, -1) am = (AT[f-1] - AM[f-1]*AMi[fm-1]*AT[fm-1])%MOD ap = (AT[fp-1] - AM[fp-1]*AMi[f-1]*AT[f-1])%MOD aa = (AT[fp-1] - AM[fp-1]*AMi[fm-1]*AT[fm-1])%MOD ans = (ans + aa - am - ap)%MOD Ans[qu] = ans print('\n'.join(map(str, Ans))) ```
91,835
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` import sys import math from collections import defaultdict from collections import deque from itertools import combinations from itertools import permutations input = lambda : sys.stdin.readline().rstrip() read = lambda : list(map(int, input().split())) def write(*args, sep="\n"): for i in args: sys.stdout.write("{}{}".format(i, sep)) INF = float('inf') MOD = 998244353 YES = "YES" NO = "NO" n = int(input()) p = [0] + read() p = list(map(lambda x : x*pow(100, MOD-2, MOD)%MOD, p)) A = [0] * (n+2) for i in range(2, n+2): A[i] = (A[i-1] - 1) * pow(p[i-1], MOD-2, MOD) % MOD print((-A[-1] + MOD) % MOD) ``` Yes
91,836
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` mod = 998244353 def pow_(x, p, mod): if p == 1: return x % mod tmp = pow_(x, p // 2, mod) if p % 2 == 0: return (tmp * tmp) % mod else: return (tmp * tmp * x) % mod def reverse(x, mod): return pow_(x, mod-2, mod) n = int(input()) + 1 p = [0] + list(map(int, input().split())) dp = [0] * n rev = [0] * 101 for i in range(1, 101): rev[i] = reverse(i, mod) for i in range(1, n): dp[i]=(((dp[i-1]+1)*100 * rev[p[i]])) % mod print(dp[-1]) ``` Yes
91,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` # 解説AC mod = 998244353 n = int(input()) p = list(map(int, input().split())) i100 = pow(100, mod-2, mod) p = [i*i100%mod for i in p] top = 1 for i in range(n-2, -1, -1): top *= p[i] top += 1 top %= mod bot = 1 for i in range(n): bot *= p[i] bot %= mod ans = top*pow(bot, mod-2, mod)%mod print(ans) ``` Yes
91,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` import sys MOD = 998244353 def powmod(a, b): if b == 0: return 1 res = powmod(a, b // 2) res *= res if b & 1: res *= a return res%MOD def inv(n): return powmod(n, MOD - 2) _100 = inv(100) n = int(input()) p = list(map(lambda x: int(x) * _100 % MOD, input().split())) if n == 1: print(inv(p[0])) sys.exit(0) pp = [0] * n pp[0] = p[0] for i in range(1, n): pp[i] = pp[i - 1] * p[i] % MOD k = 0 q = inv(pp[n - 2]) for i in range(0, n - 1): c = q if i: c *= pp[i - 1] c %= MOD k += c if k>MOD:k -= MOD res = (k + 1) * inv(p[-1]) res %= MOD print(res) ``` Yes
91,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` n=int(input()) numbers = [100/int(num) for num in input().split()] result=0 for num in numbers: if num==1: result+=1 break result+=result*(num-1)+num print(int(result)%998244353) ``` No
91,840
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` n = int(input()) ret = 0 inputs = input().split() for i in inputs: b = int(i) b = 100/b ret*=b ret+=b print(int(ret)%998244353) ``` No
91,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` def phiEuler(n): return n-1 def powerMo(a,n,mo): ans = 1 posi = a while n > 0: if n&1: ans *= posi ans %= mo n >>= 1 posi = posi*posi%mo return ans def modInv(a,mo): # return a's mod inv phi = phiEuler(mo) return(powerMo(a,phi-1,mo)) n = int(input()) P = [int(s) for s in input().split()] mo = 998244353 y = 1 for p in P: y *= p y %= mo yInv = modInv(y, mo) stop = [0]*n rem = 1 ele = modInv(100, mo) for i in range(n): stop[i] = rem*(100-P[i]) stop[i] %= mo rem = rem*P[i]*ele rem %= mo sum = 0 for i,days in enumerate(stop): sum += days*(i+1) sum += n print(sum) ``` No
91,842
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: * The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; * In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint. After each query, you need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy. Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Input The first line contains two integers n, q (2 ≤ n, q ≤ 2 ⋅ 10^5) — the number of mirrors and queries. The second line contains n integers: p_1, p_2, …, p_n (1 ≤ p_i ≤ 100). Each of q following lines contains a single integer u (2 ≤ u ≤ n) — next query. Output Print q numbers – the answers after each query by modulo 998244353. Examples Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 Note In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to 1/2. So, the expected number of days, until one mirror will say, that he is beautiful is equal to 2 and the answer will be equal to 4 = 2 + 2. Submitted Solution: ``` n = int(input()) ret = 0 inputs = input().split() for i in inputs: b = int(i) b = 100/b ret*=b ret+=b print(int(ret)) ``` No
91,843
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` import sys t = int(sys.stdin.readline()) for _ in range(t): n = int(sys.stdin.readline()) intervals = [None]*n for i in range(n): intervals[i] = tuple([int(a) for a in sys.stdin.readline().split()]) intervals = list(zip(intervals, range(n))) starts = sorted(intervals, key = lambda x: x[0][0]) ends = sorted(intervals, key = lambda x: x[0][1]) connects = [0]*n gaps = 0 covering = set() atS = 0 atE = 0 # print(starts) while atE<n: # print("%d, %d"%(atS, atE)) # print(covering) # print(connects) if atS!=n and ends[atE][0][1]>=starts[atS][0][0]: if len(covering)==1: gap = list(covering)[0] connects[gap]+=0.5 covering.add(starts[atS][1]) atS += 1 if len(covering)==1: gap = list(covering)[0] connects[gap]-=0.5 else: if len(covering)==1: gap = list(covering)[0] connects[gap]-=0.5 covering.remove(ends[atE][1]) atE += 1 if len(covering)==1: gap = list(covering)[0] connects[gap]+=0.5 if len(covering)==0: gaps += 1 connects = [int(a) for a in connects] print(max(connects)+gaps) ```
91,844
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` import sys from collections import deque def input(): return sys.stdin.readline().rstrip() t = int(input()) for _ in range(t): n = int(input()) segs = [] for i in range(n): l,r = list(map(int, input().split())) segs.append((l,0,i)) segs.append((r,1,i)) segs.sort() active = set() increase = [0 for _ in range(n)] seq = [] ans = 0 for pos, p, i in segs: if p == 0: if len(seq)>1 and seq[-2:] == [2,1]: increase[next(iter(active))]+=1 active.add(i) else: active.remove(i) if len(active) == 0: ans+=1 seq.append(len(active)) m = max(increase) seq = set(seq) if seq == {0,1}: print(ans-1) else: print(ans+max(increase)) ```
91,845
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size : _size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) def pack(a, b, c): return [a, b, c] return (a, b, c) return (a << 40) + (b << 20) + c def unpack(abc): return abc ab, c = divmod(abc, 1 << 20) a, b = divmod(ab, 1 << 20) return a, b, c def merge(x, y): # Track numClose, numNonOverlapping, numOpen: # e.g., )))) (...)(...)(...) (((((( xClose, xFull, xOpen = unpack(x) yClose, yFull, yOpen = unpack(y) if xOpen == yClose == 0: ret = xClose, xFull + yFull, yOpen elif xOpen == yClose: ret = xClose, xFull + 1 + yFull, yOpen elif xOpen > yClose: ret = xClose, xFull, xOpen - yClose + yOpen elif xOpen < yClose: ret = xClose + yClose - xOpen, yFull, yOpen # print(x, y, ret) return pack(*ret) def solve(N, intervals): endpoints = [] for i, (l, r) in enumerate(intervals): endpoints.append((l, 0, i)) endpoints.append((r, 1, i)) endpoints.sort(key=lambda t: t[1]) endpoints.sort(key=lambda t: t[0]) # Build the segment tree and track the endpoints of each interval in the segment tree data = [] # Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly? idToIndices = defaultdict(list) for x, kind, intervalId in endpoints: if kind == 0: data.append(pack(0, 0, 1)) # '(' else: assert kind == 1 data.append(pack(1, 0, 0)) # ')' idToIndices[intervalId].append(len(data) - 1) assert len(data) == 2 * N segTree = SegmentTree(data, pack(0, 0, 0), merge) # print("init", unpack(segTree.query(0, 2 * N))) best = 0 for intervalId, indices in idToIndices.items(): # Remove the two endpoints i, j = indices removed1, removed2 = segTree[i], segTree[j] segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0) # Query res = unpack(segTree.query(0, 2 * N)) assert res[0] == 0 assert res[2] == 0 best = max(best, res[1]) # print("after removing", intervals[intervalId], res) # Add back the two endpoints segTree[i], segTree[j] = removed1, removed2 return best if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] intervals = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, intervals) print(ans) ```
91,846
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` from sys import stdin input = stdin.readline q = int(input()) for rwere in range(q): n = int(input()) seg = [] pts = [] for i in range(n): pocz, kon = map(int,input().split()) seg.append([2*pocz, 2*kon]) pts.append(2*kon+1) p,k = map(list,zip(*seg)) pts += (p + k) pts.sort() ind = -1 while True: if pts[ind] == pts[-1]: ind -= 1 else: break ind += 1 pts = pts[:ind] mapa = {} val = 0 mapa[pts[0]] = val for i in range(1, len(pts)): if pts[i] != pts[i-1]: val += 1 mapa[pts[i]] = val val += 1 for i in range(n): seg[i] = [mapa[seg[i][0]], mapa[seg[i][1]]] seg.sort() dupa = [0] * (val+1) for s in seg: dupa[s[0]] += 1 dupa[s[1] + 1] -= 1 cov = [0] * val cov[0] = dupa[0] for i in range(1, val): cov[i] = cov[i-1] + dupa[i] przyn = [0] * val cur = seg[0][0] label = 1 for i in range(n): kon = seg[i][1] if cur <= kon: for j in range(cur, kon + 1): przyn[j] = label label += 1 cur = kon + 1 final = [(przyn[i] if cov[i] == 1 else (-1 if cov[i] == 0 else 0)) for i in range(val)] baza = final.count(-1) + 1 final = [-1] + final + [-1] val += 2 if max(final) <= 0: print(baza) else: comp = {} comp[0] = -100000000000 for i in final: if i > 0: comp[i] = 0 for i in range(1, val - 1): if final[i] > 0 and final[i] != final[i-1]: comp[final[i]] += 1 if final[i-1] == -1: comp[final[i]] -= 1 if final[i+1] == -1: comp[final[i]] -= 1 best = -10000000000000 for i in comp: best = max(best, comp[i]) if max(final) == n: print(baza + best) else: print(max(baza + best, baza)) ```
91,847
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` import io import os from collections import defaultdict # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size : _size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) class Node: def __init__(self, numClose, count, numOpen): self.close = numClose self.count = count self.open = numOpen neutral = Node(0, 0, 0) def combine(x, y): # Track numClose, numCount, numOpen: # e.g., )))) (...)(...)(...) (((((( if x.open == y.close == 0: ret = x.close, x.count + y.count, y.open elif x.open == y.close: ret = x.close, x.count + 1 + y.count, y.open elif x.open > y.close: ret = x.close, x.count, x.open - y.close + y.open elif x.open < y.close: ret = x.close + y.close - x.open, y.count, y.open return Node(*ret) def solve(N, intervals): OPEN = 0 CLOSE = 1 endpoints = [] for i, (l, r) in enumerate(intervals): endpoints.append((l, OPEN, i)) endpoints.append((r, CLOSE, i)) endpoints.sort(key=lambda t: t[1]) endpoints.sort(key=lambda t: t[0]) # Build the segment tree and track the endpoints of each interval in the segment tree data = [] idToIndices = defaultdict(list) for x, kind, intervalId in endpoints: if kind == OPEN: data.append(Node(0, 0, 1)) else: assert kind == CLOSE data.append(Node(1, 0, 0)) idToIndices[intervalId].append(len(data) - 1) assert len(data) == 2 * N segTree = SegmentTree(data, Node(0, 0, 0), combine) best = 0 for intervalId, indices in idToIndices.items(): # Remove the two endpoints i, j = indices removed1, removed2 = segTree[i], segTree[j] segTree[i], segTree[j] = neutral, neutral # Query res = segTree.query(0, 2 * N) assert res.open == 0 assert res.close == 0 best = max(best, res.count) # Add back the two endpoints segTree[i], segTree[j] = removed1, removed2 return best if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] intervals = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, intervals) print(ans) ```
91,848
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` import sys input = sys.stdin.readline from itertools import accumulate import random t=int(input()) for testcases in range(t): n=int(input()) S=[list(map(int,input().split())) for i in range(n)] compression_list=[] for l,r in S: compression_list.append(l) compression_list.append(r) compression_dict={a: ind for ind, a in enumerate(sorted(set(compression_list)))} for i in range(n): S[i][0]=compression_dict[S[i][0]]*2 S[i][1]=compression_dict[S[i][1]]*2 LEN=len(compression_dict)*2 R=[0]*(LEN+1) for l,r in S: R[l]+=1 R[r+1]-=1 SR=list(accumulate(R)) NOW=0 for i in range(LEN): if SR[i]!=0 and SR[i+1]==0: NOW+=1 ONECOUNT=[0]*(LEN+1) for i in range(1,LEN): if SR[i-1]!=1 and SR[i]==1: ONECOUNT[i]+=1 SO=list(accumulate(ONECOUNT)) SO.append(0) ANS=1 for l,r in S: lr=0 if SR[r]==1: lr-=1 ANS=max(ANS,NOW+SO[r-1]-SO[l]+lr) print(ANS) ```
91,849
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` def solve(lsts): points = [] for i in range(len(lsts)): points.append((lst[i][0], 0, i)) points.append((lst[i][1], 1, i)) points.sort() open = set() increased = [0] * len(lsts) original = 0 for i in range(len(points)): p = points[i] if p[1] == 0: open.add(p[2]) else: open.remove(p[2]) if len(open) == 1 and p[1] == 1 and points[i+1][1] == 0 : increased[list(open)[0]] += 1 if len(open) == 1 and p[1] == 0 and points[i+1][1] == 1: increased[list(open)[0]] -= 1 # also keep track of what was the original answer without removing if len(open) == 0: original += 1 res = -float('inf') for i in range(len(lsts)): res = max(res, increased[i]) return res + original n = int(input()) for _ in range(n): m = int(input()) lst = [] for _ in range(m): lst.append(list(map(int, input().split()))) print(solve(lst)) ```
91,850
Provide tags and a correct Python 3 solution for this coding contest problem. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers Correct Solution: ``` import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size : _size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) def pack(a, b, c): return (a, b, c) return (a << 40) + (b << 20) + c def unpack(abc): return abc ab, c = divmod(abc, 1 << 20) a, b = divmod(ab, 1 << 20) return a, b, c def merge(x, y): # Track numClose, numNonOverlapping, numOpen: # e.g., )))) (...)(...)(...) (((((( xClose, xFull, xOpen = unpack(x) yClose, yFull, yOpen = unpack(y) if xOpen == yClose == 0: ret = xClose, xFull + yFull, yOpen elif xOpen == yClose: ret = xClose, xFull + 1 + yFull, yOpen elif xOpen > yClose: ret = xClose, xFull, xOpen - yClose + yOpen elif xOpen < yClose: ret = xClose + yClose - xOpen, yFull, yOpen # print(x, y, ret) return pack(*ret) def solve(N, intervals): endpoints = [] for i, (l, r) in enumerate(intervals): endpoints.append((l, 0, i)) endpoints.append((r, 1, i)) endpoints.sort(key=lambda t: t[1]) endpoints.sort(key=lambda t: t[0]) # Build the segment tree and track the endpoints of each interval in the segment tree data = [] # Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly? idToIndices = defaultdict(list) for x, kind, intervalId in endpoints: if kind == 0: data.append(pack(0, 0, 1)) # '(' else: assert kind == 1 data.append(pack(1, 0, 0)) # ')' idToIndices[intervalId].append(len(data) - 1) assert len(data) == 2 * N segTree = SegmentTree(data, pack(0, 0, 0), merge) # print("init", unpack(segTree.query(0, 2 * N))) best = 0 for intervalId, indices in idToIndices.items(): # Remove the two endpoints i, j = indices removed1, removed2 = segTree[i], segTree[j] segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0) # Query res = unpack(segTree.query(0, 2 * N)) assert res[0] == 0 assert res[2] == 0 best = max(best, res[1]) # print("after removing", intervals[intervalId], res) # Add back the two endpoints segTree[i], segTree[j] = removed1, removed2 return best if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] intervals = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, intervals) print(ans) ```
91,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) def merge(x, y): # Track )))) ()()() (((((( # numClose, numFull, numOpen xClose, xFull, xOpen = x yClose, yFull, yOpen = y if xOpen == yClose: if xOpen: ret = xClose, xFull + 1 + yFull, yOpen else: ret = xClose, xFull + yFull, yOpen elif xOpen > yClose: ret = xClose, xFull, xOpen - yClose + yOpen elif xOpen < yClose: ret = xClose + yClose - xOpen, yFull, yOpen #print(x, y, ret) return ret def solve(N, segments): endpoints = [] for i, (l, r) in enumerate(segments): endpoints.append((l, 0, i)) endpoints.append((r, 1, i)) endpoints.sort() #print(endpoints) data = [] idToIndices = defaultdict(list) for x, kind, segmentId in endpoints: if kind == 0: data.append((0, 0, 1)) # ( else: assert kind == 1 data.append((1, 0, 0)) # ) idToIndices[segmentId].append(len(data) - 1) #print(data) assert len(data) == 2 * N segTree = SegmentTree(data, (0, 0, 0), merge) #print('init', segTree.query(0, 2 * N)) #print(segTree) best = 0 for k, indices in idToIndices.items(): # Remove the two endpoints assert len(indices) == 2 removed = [] for i in indices: removed.append(segTree[i]) segTree[i] = (0, 0, 0) res = segTree.query(0, 2 * N) assert res[0] == 0 assert res[2] == 0 #print('after removing', segments[k], 'res is', res) best = max(best, res[1]) # Add back the two endpoints for i, old in zip(indices, removed): segTree[i] = old return best if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] segments = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, segments) print(ans) ``` Yes
91,852
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ t = int(input()) for _ in range(t): n = int(input()) edges = [] for i in range(n): li, ri = map(int, input().split()) edges.append((li, 0, i)) edges.append((ri, 1, i)) edges.sort() ctr = [0] * n opened = set() segmCtr = 0 for k, (e, isEnd, i) in enumerate(edges): if isEnd: opened.remove(i) if not opened and edges[k-1][2] == i: ctr[i] -= 1 elif len(opened) == 1 and edges[k+1][1] == 0: for j in opened: ctr[j] += 1 else: if not opened: segmCtr += 1 opened.add(i) print(segmCtr + max(ctr)) # inf.close() ``` Yes
91,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size : _size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentData: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def pack(a, b, c): return SegmentData(a, b, c) # 2588 ms return [a, b, c] # 3790 ms return (a, b, c) # 3027 ms return (a << 40) + (b << 20) + c # TLE. Nicer on local because of 64-bit but cf is 32 bit def unpack(abc): return abc.a, abc.b, abc.c return abc return abc ab, c = divmod(abc, 1 << 20) a, b = divmod(ab, 1 << 20) return a, b, c def merge(x, y): # Track numClose, numNonOverlapping, numOpen: # e.g., )))) (...)(...)(...) (((((( xClose, xFull, xOpen = unpack(x) yClose, yFull, yOpen = unpack(y) if xOpen == yClose == 0: ret = xClose, xFull + yFull, yOpen elif xOpen == yClose: ret = xClose, xFull + 1 + yFull, yOpen elif xOpen > yClose: ret = xClose, xFull, xOpen - yClose + yOpen elif xOpen < yClose: ret = xClose + yClose - xOpen, yFull, yOpen # print(x, y, ret) return pack(*ret) def solve(N, intervals): endpoints = [] for i, (l, r) in enumerate(intervals): endpoints.append((l, 0, i)) endpoints.append((r, 1, i)) endpoints.sort(key=lambda t: t[1]) endpoints.sort(key=lambda t: t[0]) # Build the segment tree and track the endpoints of each interval in the segment tree data = [] # Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly? idToIndices = defaultdict(list) for x, kind, intervalId in endpoints: if kind == 0: data.append(pack(0, 0, 1)) # '(' else: assert kind == 1 data.append(pack(1, 0, 0)) # ')' idToIndices[intervalId].append(len(data) - 1) assert len(data) == 2 * N segTree = SegmentTree(data, pack(0, 0, 0), merge) # print("init", unpack(segTree.query(0, 2 * N))) best = 0 for intervalId, indices in idToIndices.items(): # Remove the two endpoints i, j = indices removed1, removed2 = segTree[i], segTree[j] segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0) # Query res = unpack(segTree.query(0, 2 * N)) assert res[0] == 0 assert res[2] == 0 best = max(best, res[1]) # print("after removing", intervals[intervalId], res) # Add back the two endpoints segTree[i], segTree[j] = removed1, removed2 return best if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] intervals = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, intervals) print(ans) ``` Yes
91,854
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import sys from math import gcd def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n = mint() a = [None]*(2*n) c = [0]*(2*n) for i in range(0,2*n,2): l, r = mints() a[i] = (l*2, 0, i) a[i+1] = (r*2+1, 1, i) c[i+1] = (l*2, r*2+1) a.sort() #print(a) s = set() p = None start = None px = int(-2e9-5) # prev event pt = -1 pp = px segs = [] for i in range(0, 2*n): x, t, id = a[i] if px != x: #print(px,x) cd = len(s) if cd == 1: segs.append((px, x, cd, next(iter(s)))) else: segs.append((px, x, cd, None)) px = x if t == 0: s.add(id) else: s.remove(id) segs.append((px,int(2e9+5), 0, None)) res = 0 p = False for i in range(1,len(segs)-1): px, x, cd, e = segs[i] if e != None: l,r = c[e+1] cl = segs[i-1][2] cr = segs[i+1][2] if cl - (segs[i-1][0] >= l) > 0 \ and cr - (segs[i-1][0] <= r) > 0: c[e] += 1 if cl == 0 and cr == 0: c[e] -= 1 if cd > 0 and p == False: res += 1 p = (cd > 0) z = c[0] for i in range(0, 2*n, 2): z = max(z, c[i]) print(res+z) for i in range(mint()): solve() ``` Yes
91,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` def solve(lsts): points = [] for i in range(len(lsts)): points.append((lst[i][0], 0, i)) points.append((lst[i][1], 1, i)) points.sort() open = set() increased = [0] * len(lsts) original = 0 for i in range(len(points)): p = points[i] if p[1] == 0: open.add(p[2]) else: open.remove(p[2]) if len(open) == 1 and p[1] == 1 and points[i+1][1] == 0 : increased[list(open)[0]] += 1 if len(open) == 1 and p[1] == 0 and points[i+1][1] == 1: increased[list(open)[0]] -= 1 # also keep track of what was the original answer without removing if len(open) == 0: original += 1 res = 0 for i in range(len(lsts)): res = max(res, increased[i]) return res + original n = int(input()) for _ in range(n): m = int(input()) lst = [] for _ in range(m): lst.append(list(map(int, input().split()))) print(solve(lst)) ``` No
91,856
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import sys from collections import deque def input(): return sys.stdin.readline().rstrip() t = int(input()) for _ in range(t): n = int(input()) segs = [] for i in range(n): l,r = list(map(int, input().split())) segs.append((l,0,i)) segs.append((r,1,i)) segs.sort() active = set() increase = [0 for _ in range(n)] seq = [] ans = 0 for pos, p, i in segs: if p == 0: if len(seq)>1 and seq[-2:] == [2,1]: increase[next(iter(active))]+=1 active.add(i) else: active.remove(i) if len(active) == 0: ans+=1 seq.append(len(active)) print(ans+max(increase)) ``` No
91,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import sys from math import gcd def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n = mint() a = [None]*(2*n) c = [0]*(2*n) for i in range(0,2*n,2): l, r = mints() a[i] = (l*2, 0, i) a[i+1] = (r*2+1, 1, i) c[i+1] = (l*2, r*2+1) a.sort() #print(a) s = set() p = None start = None px = int(-2e9-5) # prev event pt = -1 pp = px segs = [] for i in range(0, 2*n): x, t, id = a[i] if px != x: #print(px,x) cd = len(s) if cd == 1: segs.append((px, x, cd, next(iter(s)))) else: segs.append((px, x, cd, None)) px = x if t == 0: s.add(id) else: s.remove(id) segs.append((px,int(2e9+5), 0, None)) res = 0 p = False for i in range(1,len(segs)-1): px, x, cd, e = segs[i] if e != None: l,r = c[e+1] cl = segs[i-1][2] cr = segs[i+1][2] if cl - (segs[i-1][0] >= l) > 0 \ and cr - (segs[i-1][0] <= r) > 0 \ or cl == 0 and cr == 0: c[e] += 1 if cd > 0 and p == False: res += 1 p = (cd > 0) z = 0 for i in range(0, 2*n, 2): z = max(z, c[i]) print(res+z) for i in range(mint()): solve() ``` No
91,858
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r. Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible. Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: * if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; * if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments. You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible. For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: * erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; * erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; * erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2. Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow. The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5. Output Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments. Example Input 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 Output 2 1 5 Submitted Solution: ``` import sys input = sys.stdin.readline import bisect t=int(input()) for test in range(t): n=int(input()) S=[tuple(map(int,input().split())) for i in range(n)] S.append((1<<31,1<<31)) S.sort() MAX=[S[0][1]] for l,r in S[1:]: MAX.append(max(MAX[-1],r)) #print(S) #print(MAX) restmove=[0]*(n+1) for i in range(n-1,-1,-1): l,r=S[i] x=bisect.bisect_left(S,(r,1<<31)) if x-1!=i: restmove[i]=restmove[x-1] else: restmove[i]=restmove[i+1]+1 frontmove=[0]*(n+1) frontmove[0]=1 for i in range(1,n): if MAX[i-1]<S[i][0]: frontmove[i]=frontmove[i-1]+1 else: frontmove[i]=frontmove[i-1] #print(restmove) #print(frontmove) ANS=restmove[0] for i in range(1,n): l,r=S[i] if r<=MAX[i-1]: continue else: l2,r2=S[i-1] x=bisect.bisect_left(S,(MAX[i-1],1<<31)) if r2>=S[x][0]: continue else: ANS=max(ANS,restmove[x]+frontmove[i-1]) print(ANS) ``` No
91,859
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` for t in range(int(input())): d,m = [int(i) for i in input().split()] tot = 0 p = 1 while p<=d: p *= 2 p //= 2 while d>0: tot += (d-p+1)*(tot+1) tot %= m d = p-1 p //= 2 print(tot) ```
91,860
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` a=[1] for i in range(30): a.append(a[-1]*2) for t in range(int(input())): d,m=map(int,input().split()) ans=1 z=d.bit_length() for i in range(z): if i!=z-1: ans=(ans*((a[i+1]-1)-a[i]+2))%m else: ans=(ans*(d-a[i]+2))%m print((ans-1)%m) ```
91,861
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` import sys input = sys.stdin.readline t=int(input()) D=[(1<<i)-1 for i in range(1,32)] for tests in range(t): d,m=map(int,input().split()) ANS=[1] # answer for 1, 3, 7, 15, B=[0] for i in range(1,32): B.append(ANS[-1]+1) ANS.append((ANS[-1]+B[-1]*(1<<(i)))%m) for i in range(32): if d<D[i]: break #print(ANS,B) #print(i) A=ANS[i-1] #print(i,A) A=(A+(d-D[i-1])*B[i])%m print(A) ```
91,862
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` for i in range(int(input())): d, m = map(int, input().split()) a, k, s = [], 1, 1 while s < d: a.append(k) k <<= 1 s += k a.append(d - s + k) dp = [1] for j in range(len(a)): dp.append((a[j] + 1) * dp[-1]) print((dp[-1] - 1) % m) ```
91,863
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` t = int(input()) for _ in range(t): d, m = map(int, input().split()) a = [] i = 0 while d > (1<<(i+1))-1: a.append(1<<i) i += 1 a.append((1<<i) - (1<<(i+1)) + d + 1) #print(a) ans = 1 for x in a: ans *= x+1 ans %= m print((ans-1)%m) ```
91,864
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` t = int(input()) for _ in range(t): d, m = map(int, input().split()) a = [] i = 0 while d > (1<<(i+1))-1: a.append(1<<i) i += 1 a.append((1<<i) - (1<<(i+1)) + d + 1) #print(a,(1<<i) - (1<<(i+1)),d+1) ans = 1 for x in a: ans *= x+1 ans %= m #print(ans) print((ans-1)%m) ```
91,865
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` q = int(input()) for i in range(q): inp = input().split() p = int(inp[0]) n = int(inp[1]) e = 1 a = 1 t = 0 while e*2 <= p: t += e*a e *= 2 a = t+1 t %= n t += (p-e+1)*a t %= n print(t) ```
91,866
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Tags: bitmasks, combinatorics, math Correct Solution: ``` arr=[[1,1,1],[2,3,2],[4,11,6],[8,59,30],[16,539,270],[32,9179,4590],[64,302939,151470],[128,19691099,9845550],[256,2540151899,1270075950],[512,652819038299,326409519150],[1024,334896166647899,167448083323950],[2048,343268570814097499,171634285407048750],[4096,703357301598085777499,351678650799042888750],[8192,2881654864647357430417499,1440827432323678715208750],[16384,23609398306055799427410577499,11804699153027899713705288750],[32768,386839991244724273618122312337499,193419995622362136809061156168750],[65536,12676359673098369722192250052987537499,6338179836549184861096125026493768750],[131072,830770583895847856483313491722644245137499,415385291947923928241656745861322122568750],[262144,108891592742980466092837349300562149142907537499,54445796371490233046418674650281074571453768750],[524288,28545386579608614283906846932395864587067496417937499,14272693289804307141953423466197932293533748208968750],[1048576,14966032184436420774295236871338895448489030629464033937499,7483016092218210387147618435669447724244515314732016968750],[2097152,15693037129859788786248176592837924972690282270351508314081937499,7846518564929894393124088296418962486345141135175754157040968750],[4194304,32910699895996845632446722286199832870252343534114476715401877473937499,16455349947998422816223361143099916435126171767057238357700938736968750],[8388608,138037513127279049620399449518619390006863755746854020259793671698323425937499,69018756563639524810199724759309695003431877873427010129896835849161712968750],[16777216,1157942724957111181157129405826936282586087363231861356037487532551601175730145937499,578971362478555590578564702913468141293043681615930678018743766275800587865072968750],[33554432,19427056370176769979399471138639574458120108873898759284155188468412776622679791835105937499,9713528185088384989699735569319787229060054436949379642077594234206388311339895917552968750],[67108864,651863861360319626430170934556915312303502499161941367183313233065729129529675355585009227745937499,325931930680159813215085467278457656151751249580970683591656616532864564764837677792504613872968750],[134217728,43745843870408406166952773174103864509808588243421336348220398010521552280174496931781380288556373985937499,21872921935204203083476386587051932254904294121710668174110199005260776140087248465890690144278186992968750],[268435456,5871467817474786578237996065680342304630206938728110954803295012448320852599792701901164786815401204867209185937499,2935733908737393289118998032840171152315103469364055477401647506224160426299896350950582393407700602433604592968750],[536870912,1576110146844636921106782728655104702459842815602051462899328841772385696950254992040103938381099797066879922141730785937499,788055073422318460553391364327552351229921407801025731449664420886192848475127496020051969190549898533439961070865392968750]] t=int(input()) for _ in range(t): [d,m]=[int(x) for x in input().split()] for p in arr: if d>=p[0] and d<p[0]*2: print((p[1]+p[2]*(d-p[0]))%m) ```
91,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2020/7/2 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(D, M): ans = 1 for i in range(30): if D < (1 << i): break ans *= (min((1 << (i+1))-1, D) - (1 << i) + 2) ans %= M ans -= 1 if ans < 0: ans += M return ans if __name__ == '__main__': T = int(input()) ans = [] for ti in range(T): D, M = map(int, input().split()) ans.append(solve(D, M)) print('\n'.join(map(str, ans))) ``` Yes
91,868
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` t = int(input()) for _ in range(t): d,m = map(int,input().split()) pot = [1]*1000 for i in range(1,1000): pot[i] = (2*pot[i-1])%m makscyfr = 0 dd = d while dd > 0: makscyfr += 1 dd //= 2 dp = [0]*(makscyfr+1) dp[1] = 1 for i in range(2,makscyfr+1): s = 1 for j in range(1,i): s += dp[j] s *= pot[i-1] s %= m dp[i] = s ii = 0 while 2**(ii+1) <= d: ii += 1 odp = 0 for kk in range(1,makscyfr): odp += dp[kk] #a co jak a_n jest miedzy 2^ii, d mno = d+1-2**ii for j in range(1,ii+1): odp += mno*dp[j] odp += mno odp %= m print(odp) ``` Yes
91,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` def main(): # Seems like a[i] must have its most significant bit to be 1 more than that # of a[i-1]. t=int(input()) allans=[] for _ in range(t): d,m=readIntArr() dMSB=0 d2=d while d2>0: dMSB+=1 d2=d2>>1 nWaysAtThisMSB=[0 for _ in range(dMSB+1)] for msb in range(1,dMSB): nWaysAtThisMSB[msb]=pow(2,msb-1,m) #last msb only has d-(2**(dMSB-1)-1) ways nWaysAtThisMSB[dMSB]=(d-(2**(dMSB-1)-1))%m dp=[0 for _ in range(dMSB+1)] for i in range(1,dMSB+1): dp[i]+=dp[i-1] #don't take current MSB dp[i]%=m dp[i]+=nWaysAtThisMSB[i]#take current MSB alone dp[i]%=m dp[i]+=dp[i-1]*nWaysAtThisMSB[i]#take current MSB with previous items dp[i]%=m allans.append(dp[dMSB]) # print(nWaysAtThisMSB) # print(dp) multiLineArrayPrint(allans) return #import sys #input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ``` Yes
91,870
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` for _ in range(int(input())): d, m = map(int, input().split()) ans = 1 for i in range(1, 31): l = max(1, 1 << (i - 1)) r = min(d, (1 << i) - 1) #print(l, r, i) ans = (ans * (1 + (r - l + 1))) % m if r == d: break print((ans - 1 + m) % m) ``` Yes
91,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` import sys input = sys.stdin.readline if __name__ == "__main__": t = int(input()) for _ in range(t): d, m = [int(a) for a in input().split()] start = 1 end = 2 total = 1 if m == 1: print(0) continue while start <= d: total *= min(end, d+1) - start + 1 total %= m start *= 2 end *= 2 # print(total) print(total-1) # print('done') ``` No
91,872
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` def go(): d, m = map(int, input().split()) i = d.bit_length() res = 0 while i >= 0: bi = 1 << i if d >= bi: res += bitvals[i] * (d - bi + 1) res = res%m d=bi-1 i -= 1 return res%m bitvals = [1] for i in range(12): bitvals.append(bitvals[-1] * (2 ** i + 1)) print(bitvals) # x,s = map(int,input().split()) t = int(input()) # t = 1 ans = [] for _ in range(t): # print(go()) ans.append(str(go())) # print('\n'.join(ans)) ``` No
91,873
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` import sys from math import log2,floor,ceil,sqrt # import bisect # from collections import deque # from types import GeneratorType # def bootstrap(func, stack=[]): # def wrapped_function(*args, **kwargs): # if stack: # return func(*args, **kwargs) # else: # call = func(*args, **kwargs) # while True: # if type(call) is GeneratorType: # stack.append(call) # call = next(call) # else: # stack.pop() # if not stack: # break # call = stack[-1].send(call) # return call # return wrapped_function Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def input(): return sys.stdin.readline().strip() 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 INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 for _ in range(int(ri())): d,m = Ri() ans = 0 # cur= 0 prod = 1 for i in range(1,33): no = (1<<(i))-1 no = min(no,d) cut = (1<<(i-1))-1 # print(no,cut) noway = no-cut if noway <= 0: break prod = (noway+1)*prod prod = prod%m # ans = ans + prod # ans= ans%m if prod <= 0: print(0) else: print(prod-1) ``` No
91,874
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 Submitted Solution: ``` import math a=[1]*(31) for i in range(31): a[i]=1<<i t=int(input()) while t: t-=1 n,m=map(int,input().strip().split(' ')) k=int(math.log2(n)) prod=1 for i in range(k): prod=(prod*(a[i]+1))%m r=(n-a[k]+1) prod=(prod*(r+1))%m print(max(prod-1,0)) ``` No
91,875
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * #from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def lowbit(n): return n&-n def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans ''' class SMT: def __init__(self,arr): self.n=len(arr)-1 self.arr=[0]*(self.n<<2) self.lazy=[0]*(self.n<<2) def Build(l,r,rt): if l==r: self.arr[rt]=arr[l] return m=(l+r)>>1 Build(l,m,rt<<1) Build(m+1,r,rt<<1|1) self.pushup(rt) Build(1,self.n,1) def pushup(self,rt): self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1] def pushdown(self,rt,ln,rn):#lr,rn表区间数字数 if self.lazy[rt]: self.lazy[rt<<1]+=self.lazy[rt] self.lazy[rt<<1|1]+=self.lazy[rt] self.arr[rt<<1]+=self.lazy[rt]*ln self.arr[rt<<1|1]+=self.lazy[rt]*rn self.lazy[rt]=0 def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间 if r==None: r=self.n if L<=l and r<=R: self.arr[rt]+=c*(r-l+1) self.lazy[rt]+=c return m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) if L<=m: self.update(L,R,c,l,m,rt<<1) if R>m: self.update(L,R,c,m+1,r,rt<<1|1) self.pushup(rt) def query(self,L,R,l=1,r=None,rt=1): if r==None: r=self.n #print(L,R,l,r,rt) if L<=l and R>=r: return self.arr[rt] m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) ans=0 if L<=m: ans+=self.query(L,R,l,m,rt<<1) if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1) return ans ''' class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue seen.add(u) for v,w in graph[u]: if v not in d or d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj @bootstrap def gdfs(r,p): if len(g[r])==1 and p!=-1: yield None for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None def lcm(a,b): return a*b//gcd(a,b) t=N() for i in range(t): n,k=RL() f=False a=RLL() ans='no' for i in range(n): if a[i]<k: a[i]=0 elif a[i]==k: f=True if f: if n<2: ans='yes' else: pre=-inf f2=False for i in range(n): if a[i]: if i-pre<3: f2=True break pre=i if f2: ans='yes' print(ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ```
91,876
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key,lru_cache import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # import sys # input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip().split()] def st():return str(input().rstrip())[2:-1] def val():return int(input().rstrip()) def li2():return [str(i)[2:-1] for i in input().rstrip().split()] def li3():return [int(str(i)[2:-1]) for i in input().rstrip()] def do2(l): for i in range(2,len(l) + 1): if sum(l[i-2:i + 1]) > 0 or sum(l[i-2:i]) > 0:return 1 return 0 for _ in range(int(input())): n,k = [int(i) for i in input().split()] l = [int(i) for i in input().split()] if k not in l: print('NO') continue if n == 1: print('YES') continue l = [(-1 if i < k else 1) for i in l] print('YES' if do2(l) else 'NO') ```
91,877
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` import sys input=sys.stdin.buffer.readline t=int(input()) for _ in range(t): n,k=[int(x) for x in input().split()] arr=[int(x) for x in input().split()] arr.append(-1) arr.append(-1) if k not in arr: print("no") continue elif n == 1: if arr[0] == k: print("yes") continue flag=0 for i in range(n): if arr[i] >= k: if arr[i+1] >= k or arr[i+2] >= k: flag=1 if(flag): print("yes") else: print("no") ```
91,878
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` ans = [] for _ in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) if k not in a: ans.append('no') continue if n == 1: ans.append('yes' if a[0] == k else 'no') continue good = False for i in range(n - 1): if a[i] >= k and a[i + 1] >= k: good = True for i in range(1, n): if a[i] >= k and a[i - 1] >= k: good = True for i in range(1, n - 1): if a[i - 1] >= k and a[i + 1] >= k: good = True ans.append('yes' if good else 'no') print('\n'.join(ans)) ```
91,879
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` t = int(input()) for u in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) if k not in a: print("no") continue if n == 1: print("yes") continue if n == 2: if (a[0] + a[1]) / 2 >= k: print("yes") continue x = y = z = 0 ok = 0 for i in range(n): if a[i] > k: x += 1 elif a[i] < k: y += 1 else: z += 1 if i >= 3: if a[i - 3] > k: x -= 1 elif a[i - 3] < k: y -= 1 else: z -= 1 if i >= 2: if y >= 2: continue ok = 1 print("yes") break if not ok: print("no") ```
91,880
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` import sys input = sys.stdin.readline def do2(l): for i in range(2,len(l) + 1): if sum(l[i-2:i + 1]) > 0 or sum(l[i-2:i]) > 0:return 1 return 0 for _ in range(int(input())): n,k = [int(i) for i in input().split()] l = [int(i) for i in input().split()] if k not in l: print('NO') continue if n == 1: print('YES') continue l = [(-1 if i < k else 1) for i in l] print('YES' if do2(l) else 'NO') ```
91,881
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` import sys input = sys.stdin.readline for _ in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) if k not in a: print("no") continue res = False for i, x in enumerate(a): if x >= k: if i - 1 >= 0 and a[i - 1] >= k: res = True break if i + 1 < n and a[i + 1] >= k: res = True break if res: print("yes") continue if a == [k]: print("yes") continue idx = [i for i in range(n) if a[i] >= k] for j in range(len(idx) - 1): if idx[j] + 2 == idx[j + 1]: res = True break if res: print("yes") continue print("no") ```
91,882
Provide tags and a correct Python 3 solution for this coding contest problem. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Tags: constructive algorithms, greedy, math Correct Solution: ``` def ri(): return int(input()) def ria(): return list(map(int, input().split())) def solve(n, k, a): flag = False for i in range(n): if a[i] < k: a[i] = 0 elif a[i] > k: a[i] = 2 else: a[i] = 1 if a[i] == 1: flag = True if not flag: return False if n == 1: return True for i in range(n): for j in range(i+1, i+3): if j < n and a[i] and a[j]: return True return False def main(): for _ in range(ri()): n, k = ria() a = ria() print('yes' if solve(n, k, a) else 'no') if __name__ == '__main__': main() ```
91,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` import sys input = sys.stdin.readline from itertools import accumulate t = int(input()) for _ in range(t): n,k = map(int,input().split()) a = list(map(int,input().split())) if k not in a: print("no") continue if n == 1: print("yes") continue for i in range(1,n): if a[i] >= k and a[i-1] >= k: print("yes") break if i >= 2: if a[i] >= k and a[i-2] >= k: print("yes") break else: print("no") ``` Yes
91,884
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` import sys import math from collections import defaultdict # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') def solve(test): n, k = map(int, input().split()) a = list(map(int, input().split())) a += [0, 0] if n == 1 and a[0] == k: print('yes') return flag1, flag2 = 0, 0 for i in range(n): if a[i] == k: flag1 = 1 if a[i] >= k: if a[i + 1] >= k or a[i + 2] >= k: flag2 = 1 print('yes' if flag1 and flag2 else 'no') if __name__ == "__main__": test_cases = int(input()) for t in range(1, test_cases + 1): solve(t) ``` Yes
91,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` import sys ints = (int(x) for x in sys.stdin.read().split()) sys.setrecursionlimit(3000) def solve(a): n = len(a) def main(): ntc = next(ints) for tc in range(1,ntc+1): n, k = (next(ints) for i in range(2)) a = (next(ints) for i in range(n)) a = [1 if x>k else -1 if x<k else 0 for x in a] ans = 0 in a ans = ans and ( len(a)==1 or any(a[i]>=0 and a[i+1]>=0 for i in range(n-1)) or any(a[i]>=0 and a[i+2]>=0 for i in range(n-2)) ) print('yes' if ans else 'no') return main() ``` Yes
91,886
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` from sys import stdin input = stdin.buffer.readline for _ in range(int(input())): n, k = map(int, input().split()) *a, = map(int, input().split()) if k not in a: print('No') continue if n == 1: print('Yes') continue for i in range(n - 1): if a[i] >= k and a[i + 1] >= k: print('Yes') break else: for i in range(n - 2): if a[i] >= k and a[i + 2] >= k: print('Yes') break else: print('No') ``` Yes
91,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` import sys import math import bisect def main(): for _ in range(int(input())): n, m = map(int, input().split()) A = list(map(int, input().split())) ans = False if len(A) == 1 and A[0] == m: ans = True for i in range(n): if A[i] == m and i + 1 < n and A[i+1] >= A[i]: ans = True break if ans: print('yes') else: print('no') if __name__ == "__main__": main() ``` No
91,888
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` for t in range (int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) i=-1 c=0 ch=0 for j in range (n): if a[j]==k: c+=1 i=j+1 if a[j]>=k and j<n-2: for m in range (i+1,i+3): if a[m]>=k: ch=1 if a[j]>=k and j==n-2: if a[n-1]>=k: ch=1 if c>0 and (ch>0 or n==1): print("yes") else: print("no") ``` No
91,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` def main(): t = int(input()) for i in range(t): solve() def solve(): n, k = list(map(int, input().split(" "))) arr = list(map(int, input().split(" "))) if k not in arr: print('no') return if len(set(arr)) == 1: print('yes') return index = arr.index(k) if max(arr) == k: print('no') return if (0 < index) and (index < len(arr) - 1) and (arr[index + 1] >= k or arr[index - 1] >= k): print('yes') return print('no') main() ``` No
91,890
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10]. Submitted Solution: ``` ans = [] for _ in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) if k not in a: ans.append('no') continue if n == 1: ans.append('yes' if a[0] == k else 'no') continue good = False for i in range(n - 1): if a[i] >= k and a[i + 1] >= k: good = True for i in range(1, n): if a[i] >= k and a[i - 1] >= k: good = True for i in range(1, n - 1): if a[i - 1] == k and a[i + 1] == k: good = True ans.append('yes' if good else 'no') print('\n'.join(ans)) ``` No
91,891
Provide tags and a correct Python 3 solution for this coding contest problem. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Tags: dfs and similar, dp, games Correct Solution: ``` def win(s, e): if e == s:return False elif e == s + 1:return True elif e & 1:return s & 1 == 0 elif e // 2 < s:return s & 1 == 1 elif e // 4 < s:return True else:return win(s, e // 4) def lose(s, e):return (True if e // 2 < s else win(s, e // 2)) def main(): res = [False, True] for _ in range(int(input())): s, e = [int(x) for x in input().split()] if res == [True, True]: continue if res == [False, False]: continue cur = [win(s, e), lose(s, e)] if res[0]: cur = [not x for x in cur] res = cur print(*[int(x) for x in res]) main() ```
91,892
Provide tags and a correct Python 3 solution for this coding contest problem. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Tags: dfs and similar, dp, games Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase import threading from heapq import heapify,heappush,heappop def can_win(s,e): if e%2==1: return 1 if s%2==0 else 0 else: if e//2<s<=e: return 1 if s%2==1 else 0 if e//4<s<=e//2: return 1 else: return can_win(s,e//4) def main(): t=int(input()) res=[] for i in range(t): si,ei=map(int,input().split()) res.append([ can_win(si,ei) , can_win(si,ei//2) if ei>=2*si else 1 ]) # print(res) c=res f = 1; s = 0; for i in range(t): if(f == 1 and s == 1) : break if(f == 0 and s == 0) :break if(s == 1) : c[i][0]^=1 c[i][1]^=1 f = c[i][1] s = c[i][0] print(s,f) 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() ```
91,893
Provide tags and a correct Python 3 solution for this coding contest problem. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Tags: dfs and similar, dp, games Correct Solution: ``` import sys input = sys.stdin.readline def win(s, e): if e == s: return False elif e == s + 1: return True elif e & 1: return s & 1 == 0 elif e // 2 < s: return s & 1 == 1 elif e // 4 < s: return True else: return win(s, e // 4) def lose(s, e): if e // 2 < s: return True else: return win(s, e // 2) def main(): res = [False, True] for _ in range(int(input())): s, e = [int(x) for x in input().split()] if res == [True, True]: continue if res == [False, False]: continue cur = [win(s, e), lose(s, e)] if res[0]: cur = [not x for x in cur] res = cur print(*[int(x) for x in res]) main() ```
91,894
Provide tags and a correct Python 3 solution for this coding contest problem. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Tags: dfs and similar, dp, games Correct Solution: ``` def f(s,e): if e%2: return 1-s%2 elif s*2>e: return s%2 else: return g(s,e//2) def g(s,e): if 2*s>e: return 1 else: return f(s,e//2) a=[tuple(map(int,input().split())) for i in range(int(input()))] b=1 for i in a: b1=g(*i)|(f(*i)<<1) b=b1^3 if b==2 else b1 if b==0: print('0 0') exit(0) elif b==3: print('1 1') exit(0) if b==2: print('1 0') else: print('0 1') ```
91,895
Provide tags and a correct Python 3 solution for this coding contest problem. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Tags: dfs and similar, dp, games Correct Solution: ``` def win(s, e): if e % 2: return s % 2 ^ 1 if s > e // 2: return s % 2 if s > e // 4: return 1 return win(s, e // 4) def lose(s, e): if s > e // 2: return 1 return win(s, e // 2) def game(n): res = [0, 1] for i in range(n): s, e = map(int, input().split()) res[0], res[1] = res[win(s, e)], res[lose(s, e)] return res n = int(input()) print(*game(n)) ```
91,896
Provide tags and a correct Python 3 solution for this coding contest problem. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Tags: dfs and similar, dp, games Correct Solution: ``` import sys inpy = [int(x) for x in sys.stdin.read().split()] def win(s, e) : if e == s : return False if e == s+1 : return True if e % 2 == 1 : if s % 2 == 1 : return False return True q = e//4 if s <= q : return win(s, q) q = e//2 if(s > q) : return (e-s) % 2 == 1 return True def lose(s, e) : q = e//2 if(s > q) : return True else : return win(s, q) t = inpy[0] start = (True, False) inpo = 1 v = (True, True) for tc in range(t): if(inpo+1 >= len(inpy)) : print('wtf') s, e = inpy[inpo], inpy[inpo+1] inpo = inpo+2 v = ((win(s, e), lose(s, e))) if start[0] and start[1] : break if (not start[0]) and (not start[1]) : break if start[1] : v = (not v[0], not v[1]) start = (v[1], v[0]) if((start[0] != True and start[0] != False) or (start[1] != True and start[1] != False)) : print('wtf') sw = 2 if start[1] : sw = sw-1 print(1, end = ' ') else : sw = sw-1 print(0, end = ' ') if start[0] : print(1) sw = sw-1 else : print(0) sw = sw-1 if sw : print(wtf) ```
91,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Submitted Solution: ``` def win(s, e): if e % 2: return s % 2 ^ 1 if s > e // 2: return s % 2 if s > e // 4: return 1 return win(s, e // 4) def lose(s, e): if s > e // 2: return 1 return win(s, e // 2) def game(n): res = [0, 1] for i in range(n): s, e = map(int, input().split()) res[0], res[1] = res[win(s, e)], res[lose(s, e)] print(*res) return res n = int(input()) print(*game(n)) ``` No
91,898
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 ⋅ a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. Input The first line contains the integer t (1 ≤ t ≤ 10^5) — the number of rounds the game has. Then t lines follow, each contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^{18}) — the i-th round's information. The rounds are played in the same order as given in input, s_i and e_i for all rounds are known to everyone before the game starts. Output Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. Examples Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2 8 Output 1 0 Input 6 216986951114298167 235031205335543871 148302405431848579 455670351549314242 506251128322958430 575521452907339082 1 768614336404564650 189336074809158272 622104412002885672 588320087414024192 662540324268197150 Output 1 0 Note Remember, whoever writes an integer greater than e_i loses. Submitted Solution: ``` def f(s,e): if e%2: return s%2==1 elif s*2>e: return s%2==0 else: return g(s,e//2) def g(s,e): if 2*s>e: return True else: return f(s,e//2) a=[tuple(map(int,input().split())) for i in range(int(input()))] b=1 for i in a: b=(b&g(*i))|(b^(f(*i)<<1)) if b==0: print('0 0') exit(0) elif b==3: print('1 1') exit(0) if b==2: print('1 0') else: print('0 1') ``` No
91,899