message stringlengths 2 39.6k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 450 109k | cluster float64 2 2 | __index_level_0__ int64 900 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236 | instruction | 0 | 61,654 | 2 | 123,308 |
Tags: binary search, combinatorics, probabilities
Correct Solution:
```
import sys,bisect
r=lambda:map(int,sys.stdin.readline().split())
M=998244353
def f(b):return pow(b,M-2,M)
n,m=r()
d=sorted(r())
p=[0]
for v in d:p+=[p[-1]+v]
for _ in range(m):a,b=r();i=bisect.bisect_left(d,b);v=n-i; print([(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M,0][a>v])
``` | output | 1 | 61,654 | 2 | 123,309 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236 | instruction | 0 | 61,655 | 2 | 123,310 |
Tags: binary search, combinatorics, probabilities
Correct Solution:
```
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def NLI(n):return [[int(i) for i in input().split()] for i in range(n)]
def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def INP():
N=10;A=10
n=random.randint(1,N)
a=[random.randint(1,A) for i in range(n)]
return n,a
def Rtest(T):
case,err=0,0
for i in range(T):
inp=INP()
a1=naive(*inp)
a2=solve(*inp)
if a1!=a2:
print((a1,a2),inp)
err+=1
case+=1
print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:
a,b=inp;c=1
else:
a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in R(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
rt=[0]
for i in ls:rt+=[rt[-1]+i]
return rt
def bit_combination(n,base=2):
rt=[]
for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
mo=10**9+7
#mo=998244353
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
class Comb:
def __init__(self,n,mo=10**9+7):
self.fac=[0]*(n+1)
self.inv=[1]*(n+1)
self.fac[0]=1
self.fact(n)
for i in range(1,n+1):
self.fac[i]=i*self.fac[i-1]%mo
self.inv[n]*=i
self.inv[n]%=mo
self.inv[n]=pow(self.inv[n],mo-2,mo)
for i in range(1,n):
self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
return
def fact(self,n):
return self.fac[n]
def invf(self,n):
return self.inv[n]
def comb(self,x,y):
if y<0 or y>x:
return 0
return self.fac[x]*self.inv[x-y]*self.inv[y]%mo
'''
n,q=LI()
p=LI()
for i in range(n):
t,x=LI()
'''
show_flg=False
show_flg=True
ans=0
#for _ in range(I()):
mo=998244353
ans=0
n,m=LI()
d=sorted(LI())
ad=accum(d)
for i in range(m):
a,b=LI()
k=n-bisect.bisect_left(d,b)
x=n-k
'''
ans+=(k-a)*pow(k,mo-2,mo)*(ad[n]-ad[x])
ans+=(k+1-a)*pow(k+1,mo-2,mo)*(ad[x])
'''
ans=0
if a>k:
ans=0
else:
ans=((k+1)*(k-a)*(ad[n]-ad[x])+(k+1-a)*k*(ad[x]))%mo
ans*=pow((k+1)*k,mo-2,mo)
print(ans%mo)
``` | output | 1 | 61,655 | 2 | 123,311 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236 | instruction | 0 | 61,656 | 2 | 123,312 |
Tags: binary search, combinatorics, probabilities
Correct Solution:
```
import sys,bisect;r=lambda:map(int,sys.stdin.readline().split());M=998244353;f=lambda b:pow(b,M-2,M);n,m=r();d=sorted(r());p=[0]
for v in d:p+=[p[-1]+v]
for _ in range(m):a,b=r();i=bisect.bisect(d,b-1);v=n-i;print([(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M,0][a>v])
``` | output | 1 | 61,656 | 2 | 123,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236 | instruction | 0 | 61,657 | 2 | 123,314 |
Tags: binary search, combinatorics, probabilities
Correct Solution:
```
import sys,bisect
r=lambda:map(int,sys.stdin.readline().split())
M=998244353
def f(b):return pow(b,M-2,M)
n,m=r()
d=sorted(r())
p=[0]
for v in d:p+=[p[-1]+v]
o=[0]*m
for _ in range(m):
a,b=r();i=bisect.bisect_left(d,b);v=n-i
if a<=v:o[_]=(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M
print('\n'.join(map(str,o)))
``` | output | 1 | 61,657 | 2 | 123,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236 | instruction | 0 | 61,658 | 2 | 123,316 |
Tags: binary search, combinatorics, probabilities
Correct Solution:
```
import sys,bisect
r=lambda:map(int,sys.stdin.readline().split())
M=998244353
def f(b):return pow(b,M-2,M)
n,m=r()
d=sorted(r())
p=[0]
for v in d:p+=[p[-1]+v]
for _ in range(m):
a,b=r();i=bisect.bisect_left(d,b);v=n-i
print([(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M,0][a>v])
``` | output | 1 | 61,658 | 2 | 123,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted 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())
#------------------------------------------------------------------------
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
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
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 linc(f,t,l,r):
while l<r:
mid=(l+r)//2
if t>f(mid):
l=mid+1
else:
r=mid
return l
def rinc(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t<f(mid):
r=mid-1
else:
l=mid
return l
def ldec(f,t,l,r):
while l<r:
mid=(l+r)//2
if t<f(mid):
l=mid+1
else:
r=mid
return l
def rdec(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t>f(mid):
r=mid-1
else:
l=mid
return l
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def binfun(x):
c=0
for w in arr:
c+=ceil(w/x)
return c
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,l,r,arr):
self.l=l
self.r=r
self.value=(1<<31)-1 if l<r else arr[l]
mid=(l+r)//2
if(l<r):
self.left=smt(l,mid,arr)
self.right=smt(mid+1,r,arr)
self.value&=self.left.value&self.right.value
#print(l,r,self.value)
def setvalue(self,x,val):
if(self.l==self.r):
self.value=val
return
mid=(self.l+self.r)//2
if(x<=mid):
self.left.setvalue(x,val)
else:
self.right.setvalue(x,val)
self.value=self.left.value&self.right.value
def ask(self,l,r):
if(l<=self.l and r>=self.r):
return self.value
val=(1<<31)-1
mid=(self.l+self.r)//2
if(l<=mid):
val&=self.left.ask(l,r)
if(r>mid):
val&=self.right.ask(l,r)
return val
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
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it):
res=[]
for ch,g in groupby(it):
res.append((ch,len(list(g))))
return res
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
t=1
for i in range(t):
mod=998244353
n,m=RL()
d=RLL()
d.sort()
pre=[0]
for i in range(n):
pre.append((pre[-1]+d[i])%mod)
ans=pre[-1]
for i in range(m):
a,b=RL()
ind=bisect_left(d,b)
big=n-ind
if big<a:
print(0)
continue
cur=ans-((ans-pre[ind])*a%mod)*pow(big,mod-2,mod)%mod-((pre[ind]*a*pow(big+1,mod-2,mod))%mod)
cur%=mod
print(cur)
``` | instruction | 0 | 61,659 | 2 | 123,318 |
Yes | output | 1 | 61,659 | 2 | 123,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
import bisect
import sys
input=sys.stdin.readline
def inv(x):
return pow(x,998244351,998244353)
l=input().split()
n=int(l[0])
m=int(l[1])
l=input().split()
li=[int(i) for i in l]
li.sort()
pref=[]
sumi=0
for i in range(n):
sumi+=li[i]
pref.append(sumi)
for i in range(m):
ans=0
l=input().split()
a=int(l[0])
b=int(l[1])
z=bisect.bisect_left(li,b)
y=n-z
k=max(y-a,0)
if(y==0):
print(0)
continue
if(z>0):
ala=sumi-pref[z-1]
else:
ala=sumi
ans=ans+(ala*k*inv(y))
ans%=998244353
k=max(y+1-a,0)
if(z>0):
ala=pref[z-1]
else:
ala=0
ans=ans+(ala*k*inv(y+1))
ans%=998244353
print(ans)
``` | instruction | 0 | 61,660 | 2 | 123,320 |
Yes | output | 1 | 61,660 | 2 | 123,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
MOD = 998244353
import sys
from fractions import Fraction
n,m = [int(e) for e in sys.stdin.readline().split(" ")]
strengths = [int(e) for e in sys.stdin.readline().split(" ")]
defs = []
durs = []
for _ in range(m):
du,de = [int(e) for e in sys.stdin.readline().split(" ")]
defs.append(de)
durs.append(du)
"""
n,m = 20000,20000
import random
strengths = [random.randint(1,1000000) for _ in range(n)]
defs = [random.randint(1,1000000) for _ in range(m)]
durs = [random.randint(1,1000000) for _ in range(m)]
"""
strengths = list(reversed(sorted(strengths)))
prefs = [0]
for i in range(0, len(strengths)):
prefs.append(prefs[-1] + strengths[i])
#print(prefs)
def modInverse(a, m):
m0 = m
y = 0
x = 1
if (m == 1):
return 0
while (a > 1):
# q is quotient
q = a // m
t = m
# m is remainder now, process
# same as Euclid's algo
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if (x < 0):
x = x + m0
return x
def find_strength(x):
if x > strengths[0]:
return 0
if x <= strengths[-1]:
return len(strengths)
lo = 0
hi = len(strengths) - 1
mid = 0
while lo != hi:
mid = (hi + lo) // 2
#print (mid)
if strengths[mid] >= x:
if mid + 1 >= len(strengths):
return len(strengths)
if strengths[mid + 1] < x:
return mid + 1
lo = mid + 1
elif strengths[mid] < x:
hi = mid - 1
return lo + 1
def calculate(a, b):
k = find_strength(b)
if a > k:
return Fraction(0,1)
bad_m = Fraction(prefs[k], 1) * (Fraction(1,1) - Fraction(a,k))
good_m = Fraction(prefs[n] - prefs[k], 1) * (Fraction(1,1) - Fraction(a,k+1))
return bad_m + good_m
for x in range(m):
a,b = durs[x],defs[x]
F = calculate(a,b)
P,Q = F.numerator, F.denominator
sys.stdout.write(str((P * modInverse(Q,MOD)) % MOD) + "\n")
``` | instruction | 0 | 61,661 | 2 | 123,322 |
Yes | output | 1 | 61,661 | 2 | 123,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
import sys,bisect
input=sys.stdin.readline
MOD=998244353
def f(a,b):return a*pow(b,MOD-2,MOD)
n,m=map(int,input().split())
d=sorted(map(int,input().split()))
pref=[0]
for v in d:pref.append(pref[-1] + v)
out=[0]*m
for _ in range(m):
a,b=map(int,input().split());i=bisect.bisect_left(d,b)
if a<=n-i:out[_]=(pref[i]*f(n-i-a+1,n-i+1)+(pref[-1]-pref[i])*f(n-i-a,n-i))%MOD
print('\n'.join(map(str,out)))
``` | instruction | 0 | 61,662 | 2 | 123,324 |
Yes | output | 1 | 61,662 | 2 | 123,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
import sys
input = sys.stdin.readline
import bisect
n,m = map(int,input().split())
MOD = 998244353
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
d = list(map(int,input().split()))
d.sort()
dSum = [0]
for elem in d:
dSum.append(dSum[-1] + elem)
ans = [0] * m
for _ in range(m):
a,b = map(int,input().split())
l = bisect.bisect_left(d,b)
l -= 1
ans.append((dSum[l + 1] * (n - l - a) * pow(n - l,MOD-2,MOD) + (sum(d) - dSum[l + 1]) * (n - l - 1 - a) * pow(n - l - 1,MOD-2,MOD)) % MOD)
print("\n".join(map(str,ans)))
``` | instruction | 0 | 61,663 | 2 | 123,326 |
No | output | 1 | 61,663 | 2 | 123,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
n,m=map(int,input().split())
lis=list(map(int,input().split()))
for _ in range(m):
a,b=map(int,input().split())
d=0
for i in lis:
if a==0:
d+=i
elif a>0 and i>=b:
a-=1
elif a>0 and i<b:
continue
print(d%998244353)
``` | instruction | 0 | 61,664 | 2 | 123,328 |
No | output | 1 | 61,664 | 2 | 123,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def NLI(n):return [[int(i) for i in input().split()] for i in range(n)]
def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def INP():
N=10;A=10
n=random.randint(1,N)
a=[random.randint(1,A) for i in range(n)]
return n,a
def Rtest(T):
case,err=0,0
for i in range(T):
inp=INP()
a1=naive(*inp)
a2=solve(*inp)
if a1!=a2:
print((a1,a2),inp)
err+=1
case+=1
print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:
a,b=inp;c=1
else:
a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in R(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
rt=[0]
for i in ls:rt+=[rt[-1]+i]
return rt
def bit_combination(n,base=2):
rt=[]
for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
mo=10**9+7
#mo=998244353
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
class Comb:
def __init__(self,n,mo=10**9+7):
self.fac=[0]*(n+1)
self.inv=[1]*(n+1)
self.fac[0]=1
self.fact(n)
for i in range(1,n+1):
self.fac[i]=i*self.fac[i-1]%mo
self.inv[n]*=i
self.inv[n]%=mo
self.inv[n]=pow(self.inv[n],mo-2,mo)
for i in range(1,n):
self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
return
def fact(self,n):
return self.fac[n]
def invf(self,n):
return self.inv[n]
def comb(self,x,y):
if y<0 or y>x:
return 0
return self.fac[x]*self.inv[x-y]*self.inv[y]%mo
'''
n,q=LI()
p=LI()
for i in range(n):
t,x=LI()
'''
show_flg=False
show_flg=True
ans=0
#for _ in range(I()):
mo=998244353
ans=0
n,m=LI()
d=sorted(LI())
ad=accum(d)
for i in range(m):
a,b=LI()
k=n-bisect.bisect_left(d,b)
x=n-k
'''
ans+=(k-a)*pow(k,mo-2,mo)*(ad[n]-ad[x])
ans+=(k+1-a)*pow(k+1,mo-2,mo)*(ad[x])
'''
ans=0
ans=((k+1)*(k-a)*(ad[n]-ad[x])+(k+1-a)*k*(ad[x]))%mo
ans*=pow((k+1)*k,mo-2,mo)
print(ans%mo)
``` | instruction | 0 | 61,665 | 2 | 123,330 |
No | output | 1 | 61,665 | 2 | 123,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes:
* if a = 0, then you receive d damage;
* if a > 0 and d ≥ b, you receive no damage, but the current durability of the shield decreases by 1;
* if a > 0 and d < b, nothing happens.
The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of monsters and the number of shields, respectively.
The second line contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9), where d_i is the strength of the i-th monster.
Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i ≤ n; 1 ≤ b_i ≤ 10^9) — the description of the i-th shield.
Output
Print m integers, where the i-th integer represents the expected damage you receive with the i-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction x/y, where y is coprime with 998244353. You have to print the value of x ⋅ y^{-1} mod 998244353, where y^{-1} is the inverse element for y (y ⋅ y^{-1} mod 998244353 = 1).
Examples
Input
3 2
1 3 1
2 1
1 2
Output
665496237
1
Input
3 3
4 2 6
3 1
1 2
2 3
Output
0
8
665496236
Submitted Solution:
```
import sys
input = sys.stdin.readline
import bisect
n,m = map(int,input().split())
MOD = 998244353
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
d = list(map(int,input().split()))
d.sort()
dSum = [0]
for elem in d:
dSum.append(dSum[-1] + elem)
ans = [0] * m
for _ in range(m):
a,b = map(int,input().split())
l = bisect.bisect_left(d,b)
l -= 1
ans[_] = (dSum[l + 1] * (n - l - a) * pow(n - l,MOD-2,MOD) + (dSum[-1] - dSum[l + 1]) * (n - l - 1 - a) * pow(n - l - 1,MOD-2,MOD)) % MOD
print("\n".join(map(str,ans)))
``` | instruction | 0 | 61,666 | 2 | 123,332 |
No | output | 1 | 61,666 | 2 | 123,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest. | instruction | 0 | 62,342 | 2 | 124,684 |
Tags: greedy, implementation, math
Correct Solution:
```
from collections import deque
n,m = map(int, input().split())
chests = list(map(int, input().split()))
keys = list(map(int, input().split()))
evenChests = deque([x for x in chests if x % 2 == 0])
oddChests = deque([x for x in chests if x % 2 == 1])
cnt = 0
for k in keys:
if k % 2 == 1:
if evenChests:
evenChests.pop()
cnt += 1
else:
if oddChests:
oddChests.pop()
cnt += 1
print(cnt)
``` | output | 1 | 62,342 | 2 | 124,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest.
Submitted Solution:
```
from sys import stdin,stdout
if __name__ == "__main__":
write = stdout.write
stdin.readline()
chests = [int(i) for i in stdin.readline().strip().split()]
keys = [int(i) for i in stdin.readline().strip().split()]
ic = pc = ck = pk = 0
for i in chests:
if i % 2 == 0:
pc += 1
else:
ic += 1
for i in keys:
if i % 2== 0:
pk += 1
else:
ck += 1
print(min(pc,ck)+min(ic,pk))
``` | instruction | 0 | 62,347 | 2 | 124,694 |
Yes | output | 1 | 62,347 | 2 | 124,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest.
Submitted Solution:
```
n,m=map(int,input().split())
c,k=list(map(int, input().split())),list(map(int, input().split()))
c,k=[x%2 for x in c],[x%2 for x in k]
print(min(c.count(1),k.count(0))+min(c.count(0),k.count(1)))
``` | instruction | 0 | 62,348 | 2 | 124,696 |
Yes | output | 1 | 62,348 | 2 | 124,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest.
Submitted Solution:
```
import math as mt
import sys,string,bisect
input=sys.stdin.readline
from collections import deque
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
n,m=M()
l=L()
k=L()
c0,c1,k0,k1=0,0,0,0
for i in range(n):
if(l[i]%2==0):
c0+=1
else:
c1+=1
for i in range(m):
if(k[i]%2==0):
k0+=1
else:
k1+=1
print(min(c0,k1)+min(c1,k0))
``` | instruction | 0 | 62,349 | 2 | 124,698 |
Yes | output | 1 | 62,349 | 2 | 124,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest.
Submitted Solution:
```
n,m = map(int,input().split())
c = map(int,input().split())
k = map(int,input().split())
ke=0
ko=0
ce=0
co=0
for i in k:
if i%2==0:
ke+=1
else:
ko+=1
for i in c:
if i%2==0:
ce+=1
else:
co+=1
print(min(ke,co)+min(ko,ce))
``` | instruction | 0 | 62,350 | 2 | 124,700 |
Yes | output | 1 | 62,350 | 2 | 124,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest.
Submitted Solution:
```
n,m = map(int,input().split())
l = list(map(int,input().split()))
k = list(map(int,input().split()))
ans,ans2,ans3,ans4=0,0,0,0
for i in range(n):
if l[i] % 2 == 0:
ans += 1
else:
ans2 += 1
for i in range(m):
if k[i] % 2 == 0:
ans3 += 1
else:
ans4 += 1
print(min(ans,ans2) + min(ans3,ans4))
``` | instruction | 0 | 62,353 | 2 | 124,706 |
No | output | 1 | 62,353 | 2 | 124,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.
The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.
Output
Print the maximum number of chests you can open.
Examples
Input
5 4
9 14 6 2 11
8 4 7 20
Output
3
Input
5 1
2 4 6 8 10
5
Output
1
Input
1 4
10
20 30 40 50
Output
0
Note
In the first example, one possible way to unlock 3 chests is as follows:
* Use first key to unlock the fifth chest,
* Use third key to unlock the second chest,
* Use fourth key to unlock the first chest.
In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).
In the third example, no key can unlock the given chest.
Submitted Solution:
```
n,m=map(int,input().split())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
c1=c2=0
c=0
for i in l1:
if i%2!=0:
c1+=1
for i in l2:
if i%2!=0:
c2+=1
if c1!=n:
c+=min(c1,n-c1)
if c2!=n:
c+=min(c2,n-c2)
print(c)
``` | instruction | 0 | 62,354 | 2 | 124,708 |
No | output | 1 | 62,354 | 2 | 124,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.
The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.
Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:
* give the shield to the left neighbor if it exists and doesn't have a shield;
* give the shield to the right neighbor if it exists and doesn't have a shield.
In one second Peter can give exactly one order.
It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it!
Input
First line contains a single integer n (1 ≤ n ≤ 80), the number of lemmings in Peter's army.
Second line contains n integers a_i (0 ≤ a_i ≤ 1). If a_i = 1, then the i-th lemming has a shield, otherwise a_i = 0.
Output
Print \frac{n(n-1)}2 + 1 numbers, the greatest possible protection after no more than 0, 1, ..., \frac{n(n-1)}2 orders.
Examples
Input
5
1 0 0 0 1
Output
0 2 3 3 3 3 3 3 3 3 3
Input
12
0 0 0 0 1 1 1 1 0 1 1 0
Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
Note
Consider the first example.
The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.
In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, (1, 3) and (1, 4).
In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmings — (1, 3), (1, 5) and (3, 5).
You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three. | instruction | 0 | 65,055 | 2 | 130,110 |
Tags: dp, greedy
Correct Solution:
```
# import numpy as npy
# idx=sorted(idx,key=functools.cmp_to_key(cmpx))
import bisect
import array
import functools
import math
n=int(input())
a=array.array('i',map(int,input().split()))
s=0
q=[]
q.append(0)
for i in range(n):
if a[i]==1:
q.append(i+1)
s=s+1
q.append(n+1)
m=n*(n-1)//2
f=[[10000000 for i in range(82)] for i in range(3500)]
f[0][0]=0
for i in range(1,s+2):
rlim=n+1-(s+1-i)
g=[[10000000 for i in range(82)] for i in range(3500)]
for j in range(i-1,rlim+1):
for S in range(m+1):
if (f[S][j]<1000000):
for k in range(j+1,rlim+1):
nv=f[S][j]+(k-j-1)*(k-j-2)//2
nS=S+abs(k-q[i])
g[nS][k]=min(g[nS][k],nv)
f=g
mn=0
for i in range(m+1):
mn=max(mn,(n-s)*(n-s-1)//2-f[i][n+1])
print(mn,end=' ')
``` | output | 1 | 65,055 | 2 | 130,111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.
The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.
Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:
* give the shield to the left neighbor if it exists and doesn't have a shield;
* give the shield to the right neighbor if it exists and doesn't have a shield.
In one second Peter can give exactly one order.
It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it!
Input
First line contains a single integer n (1 ≤ n ≤ 80), the number of lemmings in Peter's army.
Second line contains n integers a_i (0 ≤ a_i ≤ 1). If a_i = 1, then the i-th lemming has a shield, otherwise a_i = 0.
Output
Print \frac{n(n-1)}2 + 1 numbers, the greatest possible protection after no more than 0, 1, ..., \frac{n(n-1)}2 orders.
Examples
Input
5
1 0 0 0 1
Output
0 2 3 3 3 3 3 3 3 3 3
Input
12
0 0 0 0 1 1 1 1 0 1 1 0
Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
Note
Consider the first example.
The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.
In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, (1, 3) and (1, 4).
In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmings — (1, 3), (1, 5) and (3, 5).
You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three.
Submitted Solution:
```
from math import *
``` | instruction | 0 | 65,056 | 2 | 130,112 |
No | output | 1 | 65,056 | 2 | 130,113 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.
The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.
Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:
* give the shield to the left neighbor if it exists and doesn't have a shield;
* give the shield to the right neighbor if it exists and doesn't have a shield.
In one second Peter can give exactly one order.
It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it!
Input
First line contains a single integer n (1 ≤ n ≤ 80), the number of lemmings in Peter's army.
Second line contains n integers a_i (0 ≤ a_i ≤ 1). If a_i = 1, then the i-th lemming has a shield, otherwise a_i = 0.
Output
Print \frac{n(n-1)}2 + 1 numbers, the greatest possible protection after no more than 0, 1, ..., \frac{n(n-1)}2 orders.
Examples
Input
5
1 0 0 0 1
Output
0 2 3 3 3 3 3 3 3 3 3
Input
12
0 0 0 0 1 1 1 1 0 1 1 0
Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
Note
Consider the first example.
The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.
In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, (1, 3) and (1, 4).
In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmings — (1, 3), (1, 5) and (3, 5).
You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
n=II()
aa=LI()
pre=-1
zz=[]
for i,a in enumerate(aa+[1]):
if a:
zz.append(i-pre-1)
pre=i
# print(zz)
zn=len(zz)
c0=n-(zn-1)
now=c0*(c0-1)//2-sum(z*(z-1)//2 for z in zz)
ans=[now]
# print(ans)
inf=10**9
for _ in range(n*(n-1)//2):
mx=(-1,-1,-1)
ft=(-1,-1)
sl=0
for i in range(zn-1):
sl+=zz[i]
cur=(zz[i]-zz[i+1],zz[i],inf if c0-sl==0 else (zn-i-1)/(c0-sl))
if cur>mx:
ft=(i,i+1)
mx=cur
cur = (zz[i+1]-zz[i], zz[i+1], inf if sl==0 else (i+1)/sl)
if cur > mx:
ft = (i+1, i)
mx = cur
if mx[0]>0:
now+=mx[0]-1
i,j=ft
zz[i]-=1
zz[j]+=1
ans.append(now)
# print(now,zz)
print(*ans)
``` | instruction | 0 | 65,057 | 2 | 130,114 |
No | output | 1 | 65,057 | 2 | 130,115 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.
The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.
Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:
* give the shield to the left neighbor if it exists and doesn't have a shield;
* give the shield to the right neighbor if it exists and doesn't have a shield.
In one second Peter can give exactly one order.
It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it!
Input
First line contains a single integer n (1 ≤ n ≤ 80), the number of lemmings in Peter's army.
Second line contains n integers a_i (0 ≤ a_i ≤ 1). If a_i = 1, then the i-th lemming has a shield, otherwise a_i = 0.
Output
Print \frac{n(n-1)}2 + 1 numbers, the greatest possible protection after no more than 0, 1, ..., \frac{n(n-1)}2 orders.
Examples
Input
5
1 0 0 0 1
Output
0 2 3 3 3 3 3 3 3 3 3
Input
12
0 0 0 0 1 1 1 1 0 1 1 0
Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
Note
Consider the first example.
The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.
In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, (1, 3) and (1, 4).
In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmings — (1, 3), (1, 5) and (3, 5).
You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three.
Submitted Solution:
```
t=[98]*51
for s in[*open(0)][2::2]:
for x in[0]+s.split():t[int(x)]^=1;print(*map(chr,t),sep='')
``` | instruction | 0 | 65,058 | 2 | 130,116 |
No | output | 1 | 65,058 | 2 | 130,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.
The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.
Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:
* give the shield to the left neighbor if it exists and doesn't have a shield;
* give the shield to the right neighbor if it exists and doesn't have a shield.
In one second Peter can give exactly one order.
It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each k from 0 to \frac{n(n-1)}2, if he gives no more that k orders. Help Peter to calculate it!
Input
First line contains a single integer n (1 ≤ n ≤ 80), the number of lemmings in Peter's army.
Second line contains n integers a_i (0 ≤ a_i ≤ 1). If a_i = 1, then the i-th lemming has a shield, otherwise a_i = 0.
Output
Print \frac{n(n-1)}2 + 1 numbers, the greatest possible protection after no more than 0, 1, ..., \frac{n(n-1)}2 orders.
Examples
Input
5
1 0 0 0 1
Output
0 2 3 3 3 3 3 3 3 3 3
Input
12
0 0 0 0 1 1 1 1 0 1 1 0
Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
Note
Consider the first example.
The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.
In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, (1, 3) and (1, 4).
In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmings — (1, 3), (1, 5) and (3, 5).
You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three.
Submitted Solution:
```
print(10)
``` | instruction | 0 | 65,059 | 2 | 130,118 |
No | output | 1 | 65,059 | 2 | 130,119 |
Provide a correct Python 3 solution for this coding contest problem.
The rabbit, who successfully defeated the ambushed enemy, succeeded in advancing the hero into the enemy's castle. When the hero released the cats trapped in the castle dungeon, some of them were the hero's. It will help me.
According to the cats, to reach the Demon King in the back of the castle, you will have to go through n rooms from 1 to n in this order, but one enemy is waiting in each room and you will defeat them one by one. For each of the m cats that became friends, the winning rate against each enemy in each room is known, and the main character dispatches these cats one by one to the back of the castle. Each room Can only pass after defeating the enemy there, so if one cat is killed by an enemy in one room, the next cat will fight from the enemy in that room.
The dispatched cat will proceed until it is killed by the enemy, but each time you know which room the dispatched cat was killed by the enemy, you can decide which cat to dispatch next. For example, will the cats have the greatest chance of defeating all the enemies awaiting them?
Input
The first line of input is given with m and n separated by spaces. 1 ≤ m, n ≤ 16
The next m line is given n real numbers that represent the probability that the cat will beat the enemy. The jth real number in the i + 1st line represents the probability that the cat will beat the enemy in room j. Is up to 3 digits after the decimal point.
Output
Answer the probability when you decide the order so that the cats have the maximum probability of defeating all the enemies waiting for them. The output may contain errors, but the error from the true value is 10-9. Within.
Example
Input
2 3
0.900 0.500 0.100
0.500 0.500 0.500
Output
0.372500000000 | instruction | 0 | 65,576 | 2 | 131,152 |
"Correct Solution:
```
import sys
def solve():
readline = sys.stdin.buffer.readline
write = sys.stdout.buffer.write
M, N = map(int, readline().split())
P = [list(map(float, readline().split())) + [0] for i in range(M)]
M2 = (1 << M)
dp = [[0]*(N+1) for i in range(M2)]
dp[0][N] = 1
for state in range(1, M2):
dps = dp[state]
for k in range(M):
if state & (1 << k) == 0:
continue
pk = P[k]
dpk = dp[state ^ (1 << k)]
s = 0
for i in range(N, -1, -1):
s += dpk[i] * (1 - pk[i])
dps[i] = max(dps[i], s)
s *= pk[i-1]
write(b"%.16f\n" % dp[M2-1][0])
solve()
``` | output | 1 | 65,576 | 2 | 131,153 |
Provide a correct Python 3 solution for this coding contest problem.
The rabbit, who successfully defeated the ambushed enemy, succeeded in advancing the hero into the enemy's castle. When the hero released the cats trapped in the castle dungeon, some of them were the hero's. It will help me.
According to the cats, to reach the Demon King in the back of the castle, you will have to go through n rooms from 1 to n in this order, but one enemy is waiting in each room and you will defeat them one by one. For each of the m cats that became friends, the winning rate against each enemy in each room is known, and the main character dispatches these cats one by one to the back of the castle. Each room Can only pass after defeating the enemy there, so if one cat is killed by an enemy in one room, the next cat will fight from the enemy in that room.
The dispatched cat will proceed until it is killed by the enemy, but each time you know which room the dispatched cat was killed by the enemy, you can decide which cat to dispatch next. For example, will the cats have the greatest chance of defeating all the enemies awaiting them?
Input
The first line of input is given with m and n separated by spaces. 1 ≤ m, n ≤ 16
The next m line is given n real numbers that represent the probability that the cat will beat the enemy. The jth real number in the i + 1st line represents the probability that the cat will beat the enemy in room j. Is up to 3 digits after the decimal point.
Output
Answer the probability when you decide the order so that the cats have the maximum probability of defeating all the enemies waiting for them. The output may contain errors, but the error from the true value is 10-9. Within.
Example
Input
2 3
0.900 0.500 0.100
0.500 0.500 0.500
Output
0.372500000000 | instruction | 0 | 65,577 | 2 | 131,154 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f(n,m):
a = [LF() for _ in range(n)]
b = []
mx = 1 << n
for i in range(mx):
t = []
for j in range(n):
if i & (1<<j):
t.append(j)
b.append(t)
nmx = n * mx
ca = [1] * nmx
cn = [c<<n for c in range(n)]
ci = [1<<c for c in range(n)]
for k in range(1,m+1):
ka = [a[c][-k] for c in range(n)]
na = [0] * nmx
re = [0] * mx
for x in range(1,mx):
for c in b[x]:
y = cn[c] + x
na[y] = ka[c] * ca[y] + (1 - ka[c]) * re[x - ci[c]]
if re[x] < na[y]:
re[x] = na[y]
ca = na
return '{:0.10f}'.format(max(ca))
while 1:
n,m = LI()
if n == 0:
break
rr.append(f(n,m))
break
return '\n'.join(map(str, rr))
print(main())
``` | output | 1 | 65,577 | 2 | 131,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.
The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer — the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs. | instruction | 0 | 65,770 | 2 | 131,540 |
Tags: bitmasks, math
Correct Solution:
```
input=__import__('sys').stdin.readline
for _ in range(int(input())):
n=int(input())
s=list(map(int,input().split()))
ans=0
bt=[0]*40
for i in s:
mb=1
j=0
while mb*2<=i:mb*=2;j+=1
ans+=bt[j]
bt[j]+=1
print(ans)
``` | output | 1 | 65,770 | 2 | 131,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.
The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer — the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs. | instruction | 0 | 65,773 | 2 | 131,546 |
Tags: bitmasks, math
Correct Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
counts = [0] * 32
for x in a:
counts[len(bin(x))-2] += 1
total = 0
for count in counts:
total += count * (count-1) // 2
print(total)
``` | output | 1 | 65,773 | 2 | 131,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.
The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer — the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs. | instruction | 0 | 65,774 | 2 | 131,548 |
Tags: bitmasks, math
Correct Solution:
```
from collections import Counter
for _ in range(int(input())):
n=int(input())
a=[int(i) for i in input().split()]
bt=[len(bin(i)[2:]) for i in a]
d=Counter(bt); ans=0
for i in d:
ans+=(d[i]*(d[i]-1)//2)
print(ans)
``` | output | 1 | 65,774 | 2 | 131,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.
The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer — the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs. | instruction | 0 | 65,775 | 2 | 131,550 |
Tags: bitmasks, math
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().rstrip().split(" ")))
d = {}
for i in range(n):
a = bin(l[i])
z = len(a) - 2
if not d.get(z, 0):
d[z]=0
d[z]+=1
res = 0
for i in d.values():
res += (((i-1)*i)//2)
print(res)
``` | output | 1 | 65,775 | 2 | 131,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.
The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer — the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs. | instruction | 0 | 65,776 | 2 | 131,552 |
Tags: bitmasks, math
Correct Solution:
```
from sys import stdin, stdout
input = stdin.readline
print = lambda x:stdout.write(str(x)+'\n')
from collections import defaultdict
for _ in range(int(input())):
n = int(input())
cnt = defaultdict(int)
for i in map(int, input().split()):
cnt[len(bin(i))-2] += 1
ans = 0
for i in cnt:
if cnt[i]>1:
ans += cnt[i]*(cnt[i]-1)//2
print(ans)
``` | output | 1 | 65,776 | 2 | 131,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.
The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For every test case print one non-negative integer — the answer to the problem.
Example
Input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
Output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs. | instruction | 0 | 65,777 | 2 | 131,554 |
Tags: bitmasks, math
Correct Solution:
```
from collections import defaultdict,deque
import heapq as hq
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int,input().split()))
ans = 0
for bit in range(32,-1,-1):
count = 0
for i in range(n):
num = arr[i]
if (num!=-1) and (num&(1<<bit)):
#print(f'for bit={bit} num is {num}')
count+=1
arr[i] = -1
#print(arr)
ans += (count * (count-1))//2
print(ans)
``` | output | 1 | 65,777 | 2 | 131,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 ≤ n.
* to get 20 points, you need to solve the problem with constraints: n ≤ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n ≤ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n ≤ 1018 (subproblems C1+C2+C3).
Output
Print a single integer — the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 → 20 → 18 → 10 → 9 → 0 | instruction | 0 | 65,908 | 2 | 131,816 |
Tags: dp
Correct Solution:
```
c = '0123456789'
F = {c[a] + c[b]: (c[10 - a + b], 1) if a > b else (c[10 - a], 2) for a in range(1, 10) for b in range(10)}
for b in range(1, 10): F['0' + c[b]] = ('0', 1)
F['00'] = ('0', 0)
def f(x):
global F
if x in F: return F[x]
a, b, y, s = int(x[0]), int(x[1]), x[2: ], 0
for i in range(b, a, -1):
y, d = f(c[i] + y)
s += d
for i in range(min(a, b) + 1):
y, d = f(x[0] + y)
s += d
F[x] = ('9' + y, s)
return F[x]
print(f('0' + input())[1])
``` | output | 1 | 65,908 | 2 | 131,817 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 ≤ n.
* to get 20 points, you need to solve the problem with constraints: n ≤ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n ≤ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n ≤ 1018 (subproblems C1+C2+C3).
Output
Print a single integer — the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 → 20 → 18 → 10 → 9 → 0 | instruction | 0 | 65,909 | 2 | 131,818 |
Tags: dp
Correct Solution:
```
memoization_table = {}
def compute_count(previous_max, rest):
global memoization_table
original_rest = rest
if (previous_max, rest) in memoization_table:
return memoization_table[(previous_max, rest)]
num_digits = len(str(rest))
if num_digits == 1:
memoization_table[(previous_max, original_rest)] = 1, min(0, rest-previous_max)
return 1, min(0, rest-previous_max)
sum_count = 0
while rest > 0:
s = str(rest).zfill(num_digits)
new_max = max(previous_max, int(s[0]))
new_rest = int(s[1:])
count, leftover = compute_count(new_max, new_rest)
sum_count += count
rest -= new_rest
rest += leftover
memoization_table[(previous_max, original_rest)] = sum_count, rest
return sum_count, rest
n=int(input())
ans=0
if n != 0: ans,not_ans=compute_count(0,n)
print(ans)
``` | output | 1 | 65,909 | 2 | 131,819 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 ≤ n.
* to get 20 points, you need to solve the problem with constraints: n ≤ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n ≤ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n ≤ 1018 (subproblems C1+C2+C3).
Output
Print a single integer — the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 → 20 → 18 → 10 → 9 → 0 | instruction | 0 | 65,910 | 2 | 131,820 |
Tags: dp
Correct Solution:
```
#COPIED
memoization_table = {}
def compute_count(previous_max, rest):
global memoization_table
original_rest = rest
if (previous_max, rest) in memoization_table:
return memoization_table[(previous_max, rest)]
num_digits = len(str(rest))
if num_digits == 1:
memoization_table[(previous_max, original_rest)] = 1, min(0, rest-previous_max)
return 1, min(0, rest-previous_max)
sum_count = 0
while rest > 0:
s = str(rest).zfill(num_digits)
new_max = max(previous_max, int(s[0]))
new_rest = int(s[1:])
count, leftover = compute_count(new_max, new_rest)
sum_count += count
rest -= new_rest
rest += leftover
memoization_table[(previous_max, original_rest)] = sum_count, rest
return sum_count, rest
n=int(input())
ans=0
if n != 0: ans,not_ans=compute_count(0,n)
print(ans)
``` | output | 1 | 65,910 | 2 | 131,821 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too. | instruction | 0 | 66,452 | 2 | 132,904 |
Tags: bitmasks, brute force, data structures
Correct Solution:
```
from sys import stdin
def main():
n, m, q = map(int, input().split())
c = sz = 1 << n
costs, cnt = [0] * sz, [0] * sz
for w in map(int, input().split()):
c //= 2
for i in range(c, sz, c * 2):
for j in range(i, i + c):
costs[j] += w
for i, c in enumerate(costs):
if c > 101:
costs[i] = 101
costs.reverse()
l = stdin.read().splitlines()
for s in l[:m]:
cnt[int(s, 2)] += 1
del l[:m]
cache = []
for i in range(sz):
row = [0] * 102
cache.append(row)
for j, c in enumerate(cnt):
row[costs[i ^ j]] += c
a = 0
for j, b in enumerate(row):
a += b
row[j] = a
for i, s in enumerate(l):
row = s.split()
l[i] = str(cache[int(row[0], 2)][int(row[1])])
print('\n'.join(l))
if __name__ == '__main__':
main()
``` | output | 1 | 66,452 | 2 | 132,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too. | instruction | 0 | 66,453 | 2 | 132,906 |
Tags: bitmasks, brute force, data structures
Correct Solution:
```
import sys
from collections import Counter
n,m,q=map(int,sys.stdin.readline().split())
w=list(map(int,sys.stdin.readline().split()))
S=[int(sys.stdin.readline(),2) for i in range(m)]
Q=[tuple(sys.stdin.readline().split()) for i in range(q)]
counter=Counter(S)
stmax=100
re=2**n
w.reverse()
score=[None]*(re)
for i in range(re):
ANS=0
for j in range(n):
if i &(1<<j)==0:
ANS+=w[j]
score[i]=ANS
STN=[[0 for j in range(stmax+1)] for i in range(re)]
for i in range(re):
for j in range(re):
if score[i^j]<=stmax:
STN[i][score[i^j]]+=counter[j]
for j in range(1,stmax+1):
STN[i][j]=STN[i][j]+STN[i][j-1]
for q in Q:
sys.stdout.write(str(STN[int(q[0],2)][int(q[1])])+"\n")
``` | output | 1 | 66,453 | 2 | 132,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too. | instruction | 0 | 66,454 | 2 | 132,908 |
Tags: bitmasks, brute force, data structures
Correct Solution:
```
import sys
n, m, q = map(int, sys.stdin.readline().strip().split())
w = [int(x) for x in sys.stdin.readline().strip().split()]
mx = pow(2, n)
mask = mx-1
sn = [0]*mx
for i in range(m):
s = sys.stdin.readline().strip()
si = int(s, 2)
sn[si] += 1
wu = [0]*mx
for i in range(mx):
for j in range(n):
if (1<<j)&i != 0:
wu[i] += w[n-j-1]
c = []
for i in range(mx):
c.append([0]*102)
for j in range(mx):
join = (~i^j)&mask
val = wu[join]
if val > 100: val = 101
c[i][val] += sn[j]
for j in range(1, 102):
c[i][j] += c[i][j-1]
for i in range(q):
row = sys.stdin.readline().strip().split()
t = int(row[0], 2)
k = int(row[1])
sys.stdout.write(str(c[t][k])+'\n')
``` | output | 1 | 66,454 | 2 | 132,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too. | instruction | 0 | 66,455 | 2 | 132,910 |
Tags: bitmasks, brute force, data structures
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(200001)]
pp=[0]*200001
def SieveOfEratosthenes(n=200000):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
#---------------------------------running code------------------------------------------
n, m, q = map(int, input().split())
c = sz = 1 << n
costs, cnt = [0] * sz, [0] * sz
for w in map(int, input().split()):
c //= 2
for i in range(c, sz, c * 2):
for j in range(i, i + c):
costs[j] += w
for i, c in enumerate(costs):
if c > 101:
costs[i] = 101
costs.reverse()
l = sys.stdin.read().splitlines()
for s in l[:m]:
cnt[int(s, 2)] += 1
del l[:m]
cache = []
for i in range(sz):
row = [0] * 102
cache.append(row)
for j, c in enumerate(cnt):
row[costs[i ^ j]] += c
a = 0
for j, b in enumerate(row):
a += b
row[j] = a
for i, s in enumerate(l):
row = s.split()
l[i] = str(cache[int(row[0], 2)][int(row[1])])
print('\n'.join(l))
``` | output | 1 | 66,455 | 2 | 132,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too.
Submitted Solution:
```
def theWu():
n,m,q = map(int, input().split())
w = list(map(int, input().split()))
S = []
query = []
for i in range(m):
string = (input().split())
S.append(string)
for j in range(q):
queryItem = input().split()
query.append(queryItem)
# iterate through items in query
for queryitem in query:
queryAns = 0
Qcompare = queryitem[0]
k = queryitem[1]
# compare with each item in multiset
for multisetItem in S:
Mcompare = multisetItem[0]
total = 0
for i in range(n):
if Mcompare[i] == Qcompare[i]:
total += w[i]
if total <= int(k):
queryAns += 1
print (queryAns)
``` | instruction | 0 | 66,456 | 2 | 132,912 |
No | output | 1 | 66,456 | 2 | 132,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too.
Submitted Solution:
```
import time
start_time = time.time()
[n,m,q] = [int(x) for x in input().split(" ")]
w = [int(x) for x in input().split(" ")]
s = [int(input(),2) for x in range(m)]
queries = [input() for x in range(q)]
#shift to 12
w = [0]*(12-len(w))+w
coefficient = 2**(12-n)
n=12
def bts(num):
a = bin(num)[2:]
return "0"*(6-len(a))+a
def dp(s1,s2):
return sum([int(s1[i])*s2[i] for i in range(len(s1))])
#f[t1][t2][k]: number of string endings match front and weight of back = k
f = [[0]*101 for _ in range(4096)]
for s1 in s:
for j in range(64):
k = dp(bts(64-1-j^int(s1%64)),w[-6:])
for i in range(64):
k1 = 100 if k>100 else k
f[64*i+j][k1] += 1
print("--- %s seconds ---" % (time.time() - start_time))
g = [[0]*101 for _ in range(4096)]
for s1 in s:
for i in range(64):
k = dp(bts(64-1-i^int(s1/64)),w[:6])
for j in range(64):
g[64*i+j][k] = f[64*i+j][0]
for k1 in range(k+1,101):
g[64*i+j][k1] = g[64*i+j][k1-1] + f[64*i+j][k1-k]
for qu in queries:
[t,k] = qu.split(" ")
t=int(t,2)
k = int(k)
print(g[t][k])
``` | instruction | 0 | 66,457 | 2 | 132,914 |
No | output | 1 | 66,457 | 2 | 132,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too.
Submitted Solution:
```
n,m,q=map(int,input().split())
w=list(map(int,input().split()))
ms=[]
for i in range(m):
ms.append(input())
ds={x:ms.count(x) for x in ms}
ms=list(set(ms))
cs=list(ds.values())
qs=dict()
for i in range(q):
s,k=list(input().split())
k=int(k)
if s not in list(qs.keys()):
temp=[]
for str in ms:
sum=0
for i in range(n):
if str[i]==s[i]:
sum+=w[i]
temp.append(sum)
qs[s]=temp
sum=0
temp=qs[s]
for j in range(len(cs)):
if temp[j]<=k:
sum+=1*(cs[j])
print(sum)
``` | instruction | 0 | 66,458 | 2 | 132,916 |
No | output | 1 | 66,458 | 2 | 132,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too.
Submitted Solution:
```
[n,m,q] = [int(x) for x in input().split(" ")]
w = [int(x) for x in input().split(" ")]
s = [int(input(),2) for x in range(m)]
queries = [input() for x in range(q)]
#shift to 12
w = [0]*(12-len(w))+w
coefficient = 2**(12-n)
n=12
def bts(num):
a = bin(num)[2:]
return "0"*(6-len(a))+a
def dp(s1,s2):
return sum([int(s1[i])*s2[i] for i in range(len(s1))])
#f[t1][t2][k]: number of string endings match front and weight of back = k
f = [[0]*101 for _ in range(64)]
#precompute s
s0 = [0]*64
for s1 in s:
s0[s1%64] += 1
for s1 in range(64):
for j in range(64):
k = dp(bts(64-1-j^int(s1%64)),w[-6:])
k1 = 100 if k>100 else k
f[j][k1] += s0[s1]
f2 = [[0]*101 for _ in range(64)]
for j in range(64):
for k in range(101):
if k == 0:
f2[j][k] = f[j][0]
else:
f2[j][k] = f2[j][k-1]+f[j][k]
g = [0]*4096
s2 = [0]*64
for s3 in s:
s2[int(s3/64)] += 1
for s3 in range(64):
for i in range(64):
g[64*i+j] = dp(bts(64-1-i^s3),w[:6])
for qu in queries:
[t,k] = qu.split(" ")
t=int(t,2)
k = int(k)
print(f2[j][(k-g[t])] if k >= g[t] else 0)
``` | instruction | 0 | 66,459 | 2 | 132,918 |
No | output | 1 | 66,459 | 2 | 132,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n officers in the Army of Byteland. Each officer has some power associated with him. The power of the i-th officer is denoted by p_{i}. As the war is fast approaching, the General would like to know the strength of the army.
The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these n officers and calls this subset a battalion.(All 2^n subsets of the n officers can be chosen equally likely, including empty subset and the subset of all officers).
The strength of a battalion is calculated in the following way:
Let the powers of the chosen officers be a_{1},a_{2},…,a_{k}, where a_1 ≤ a_2 ≤ ... ≤ a_k. The strength of this battalion is equal to a_1a_2 + a_2a_3 + ... + a_{k-1}a_k. (If the size of Battalion is ≤ 1, then the strength of this battalion is 0).
The strength of the army is equal to the expected value of the strength of the battalion.
As the war is really long, the powers of officers may change. Precisely, there will be q changes. Each one of the form i x indicating that p_{i} is changed to x.
You need to find the strength of the army initially and after each of these q updates.
Note that the changes are permanent.
The strength should be found by modulo 10^{9}+7. Formally, let M=10^{9}+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and qnot≡ 0 mod 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 mod M).
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 3⋅10^{5}) — the number of officers in Byteland's Army.
The second line contains n integers p_{1},p_{2},…,p_{n} (1 ≤ p_{i} ≤ 10^{9}).
The third line contains a single integer q (1 ≤ q ≤ 3⋅10^{5}) — the number of updates.
Each of the next q lines contains two integers i and x (1 ≤ i ≤ n, 1 ≤ x ≤ 10^{9}), indicating that p_{i} is updated to x .
Output
In the first line output the initial strength of the army.
In i-th of the next q lines, output the strength of the army after i-th update.
Examples
Input
2
1 2
2
1 2
2 1
Output
500000004
1
500000004
Input
4
1 2 3 4
4
1 5
2 5
3 5
4 5
Output
625000011
13
62500020
375000027
62500027
Note
In first testcase, initially, there are four possible battalions
* {} Strength = 0
* {1} Strength = 0
* {2} Strength = 0
* {1,2} Strength = 2
So strength of army is (0+0+0+2)/(4) = 1/2
After changing p_{1} to 2, strength of battallion {1,2} changes to 4, so strength of army becomes 1.
After changing p_{2} to 1, strength of battalion {1,2} again becomes 2, so strength of army becomes 1/2.
Submitted Solution:
```
def expected(n,lel):
ex = 0
a = sorted(lel)
for j in range(2,n+1):
for i in range(1,j):
ex += a[i-1]*a[j-1]*pow(2,n-j)*pow(2,i-1)
exp = (ex*pow(pow(2,n),1000000005,1000000007))%(1000000007)
print(exp)
n = int(input())
line1 = input()
rank = list(map(int, line1.split(" ")))
print(rank)
expected(n,rank)
updates = int(input())
for j in range(updates):
line = input()
temparr = list(map(int, line.split(" ")))
k = temparr[0]
x = temparr[1]
rank[k-1] = x
print(rank)
expected(n,rank)
``` | instruction | 0 | 66,571 | 2 | 133,142 |
No | output | 1 | 66,571 | 2 | 133,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe — w units. You don't care what to take, since each of them will melt into one steel ingot.
What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers p and f (1 ≤ p, f ≤ 10^9) — yours and your follower's capacities.
The second line of each test case contains two integers cnt_s and cnt_w (1 ≤ cnt_s, cnt_w ≤ 2 ⋅ 10^5) — the number of swords and war axes in the shop.
The third line of each test case contains two integers s and w (1 ≤ s, w ≤ 10^9) — the weights of each sword and each war axe.
It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.
Example
Input
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
Output
11
20
3
Note
In the first test case:
* you should take 3 swords and 3 war axes: 3 ⋅ 5 + 3 ⋅ 6 = 33 ≤ 33
* and your follower — 3 swords and 2 war axes: 3 ⋅ 5 + 2 ⋅ 6 = 27 ≤ 27.
3 + 3 + 3 + 2 = 11 weapons in total.
In the second test case, you can take all available weapons even without your follower's help, since 5 ⋅ 10 + 5 ⋅ 10 ≤ 100.
In the third test case, you can't take anything, but your follower can take 3 war axes: 3 ⋅ 5 ≤ 19. | instruction | 0 | 66,620 | 2 | 133,240 |
Tags: brute force, greedy, math
Correct Solution:
```
import sys
input=sys.stdin.readline
for _ in range(int(input())):
p,f=map(int,input().split())
c1,c2=map(int,input().split())
s,w=map(int,input().split())
xx=min(c1,p//s)
ans=0
for i in range(0,xx+1):
tem=0
cc=p-s*i
tem+=i
axe=min(c2,cc//w)
tem+=axe
left=c2-axe
if(s<=w):
swo=min(c1-i,f//s)
tem+=swo
cc=f-swo*s
tem+=min(left,cc//w)
else:
axe=min(left,f//w)
tem+=axe
cc=f-axe*w
tem+=min(c1-i,cc//s)
ans=max(ans,tem)
print(ans)
``` | output | 1 | 66,620 | 2 | 133,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe — w units. You don't care what to take, since each of them will melt into one steel ingot.
What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers p and f (1 ≤ p, f ≤ 10^9) — yours and your follower's capacities.
The second line of each test case contains two integers cnt_s and cnt_w (1 ≤ cnt_s, cnt_w ≤ 2 ⋅ 10^5) — the number of swords and war axes in the shop.
The third line of each test case contains two integers s and w (1 ≤ s, w ≤ 10^9) — the weights of each sword and each war axe.
It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.
Example
Input
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
Output
11
20
3
Note
In the first test case:
* you should take 3 swords and 3 war axes: 3 ⋅ 5 + 3 ⋅ 6 = 33 ≤ 33
* and your follower — 3 swords and 2 war axes: 3 ⋅ 5 + 2 ⋅ 6 = 27 ≤ 27.
3 + 3 + 3 + 2 = 11 weapons in total.
In the second test case, you can take all available weapons even without your follower's help, since 5 ⋅ 10 + 5 ⋅ 10 ≤ 100.
In the third test case, you can't take anything, but your follower can take 3 war axes: 3 ⋅ 5 ≤ 19. | instruction | 0 | 66,621 | 2 | 133,242 |
Tags: brute force, greedy, math
Correct Solution:
```
from collections import defaultdict as dc
import sys
from collections import Counter as cnt
from collections import deque as dq
from copy import copy,deepcopy
import itertools
import math
mod=10**9 +7
# How to sort a list using two compare :
# instead of defining a function define class as a key
# class key(str):
# def __lt__(x,y):
# return int(x+y)>int(y+x)
def sinp():
p=str(sys.stdin.readline())
return p
def seive(n):
p=[0]*(n+1)
for i in range(2,n):
for j in range(2*i,n+1,i):
p[i]=1
return p
def inp():
p=int(sys.stdin.readline())
return p
def line():
p=list(map(int,sys.stdin.readline().split()))
return p
def read_mat():
n=inp()
a=[]
for i in range(n):
a.append(line())
return a
def ind(a):
return ord(a)-ord('A')
def digit(n):
p=[int(i) for i in str(n)]
return p
def check(p,n):
l=str(p)
s=''
for i in range(n):
s=s+bin(int(l[i]))[2:]
s=s[:-n]
if s=='':
return 0
return int(s,2)
def createcomb(a,n,i):
if i==n:
ans.append(a)
else:
for z in range(n):
a.append(a[z])
createcomb(a,n,z)
a.pop()
def solve(a,n,a1,b1,c1):
l=[]
r=[]
x=0
for i in range(n):
if a[i]>=x:
l.append(i)
x=a[i]
x=0
for i in range(n-1,-1,-1):
if a[i]>=x:
r.append(i)
x=a[i]
z=cnt(r)
c=0
p=len(l)
q=len(r)
for i in l:
if z[i]:
c+=1
if p==a1 and q==b1 and c1==c:
return 1
return 0
def xor(a,b):
s=''
for i in range(len(a)):
if a[i]=='1' and b[i]=='0':
s+='1'
elif b[i]=='1' and a[i]=='0':
s+='1'
else:
s+='0'
return s
for t in range(inp()):
p,f=line()
cnts,cntw=line()
s,w=line()
ans=0
l=0
def extra(s,w,cnts,cntw,f):
if s>w:
return extra(w,s,cntw,cnts,f)
if s*cnts>=f:
return f//(s)
return cnts+(min((f-(s*cnts))//w,cntw))
for x in range(0,cnts+1):
y1=max(0,p-(x*s))
z=min(y1//w,cntw)
if (x*s+w*z <=p):
ans=max(ans,x+z+extra(s,w,cnts-x,cntw-z,f))
print(ans)
``` | output | 1 | 66,621 | 2 | 133,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe — w units. You don't care what to take, since each of them will melt into one steel ingot.
What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers p and f (1 ≤ p, f ≤ 10^9) — yours and your follower's capacities.
The second line of each test case contains two integers cnt_s and cnt_w (1 ≤ cnt_s, cnt_w ≤ 2 ⋅ 10^5) — the number of swords and war axes in the shop.
The third line of each test case contains two integers s and w (1 ≤ s, w ≤ 10^9) — the weights of each sword and each war axe.
It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.
Example
Input
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
Output
11
20
3
Note
In the first test case:
* you should take 3 swords and 3 war axes: 3 ⋅ 5 + 3 ⋅ 6 = 33 ≤ 33
* and your follower — 3 swords and 2 war axes: 3 ⋅ 5 + 2 ⋅ 6 = 27 ≤ 27.
3 + 3 + 3 + 2 = 11 weapons in total.
In the second test case, you can take all available weapons even without your follower's help, since 5 ⋅ 10 + 5 ⋅ 10 ≤ 100.
In the third test case, you can't take anything, but your follower can take 3 war axes: 3 ⋅ 5 ≤ 19. | instruction | 0 | 66,622 | 2 | 133,244 |
Tags: brute force, greedy, math
Correct Solution:
```
import time,math as mt,bisect as bs,sys
from sys import stdin,stdout
from collections import defaultdict
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IO(): # to take string input
return stdin.readline()
def IP(): # to take tuple as input
return map(int,stdin.readline().split())
def L(): # to take list as input
return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
if a==0:
return b
elif b==0:
return a
if a>b:
return gcd(a%b,b)
else:
return gcd(a,b%a)
def readTree(): # to read tree
v=int(input())
adj=[set() for i in range(v+1)]
for i in range(v-1):
u1,u2=In()
adj[u1].add(u2)
adj[u2].add(u1)
return adj,v
def bfs(adj,v): # a schema of bfs
visited=[False]*(v+1)
q=deque()
while q:
pass
def sieve():
li=[True]*1000001
li[0],li[1]=False,False
for i in range(2,len(li),1):
if li[i]==True:
for j in range(i*i,len(li),i):
li[j]=False
prime=[]
for i in range(1000001):
if li[i]==True:
prime.append(i)
return prime
def setBit(n):
count=0
while n!=0:
n=n&(n-1)
count+=1
return count
mx=10**7
spf=[mx]*(mx+1)
def SPF():
spf[1]=1
for i in range(2,mx+1):
if spf[i]==mx:
spf[i]=i
for j in range(i*i,mx+1,i):
if i<spf[j]:
spf[j]=i
return
#####################################################################################
mod=10**9+7
def solve():
p,f=IP()
c1,c2=IP()
w1,w2=IP()
if w1>w2:
w1,w2=w2,w1
c1,c2=c2,c1
ans=-1e9
for i in range(c1+1):
if (p-i*w1)>=0:
a2=min(c2,(p-i*w1)//w2)
a3=min(c1-i,f//w1)
a4=min(c2-a2,(f-a3*w1)//w2)
ans=max(ans,i+a2+a3+a4)
print(ans)
return
t=II()
for i in range(t):
solve()
#######
#
#
####### # # # #### # # #
# # # # # # # # # # #
# #### # # #### #### # #
###### # # #### # # # # #
``` | output | 1 | 66,622 | 2 | 133,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe — w units. You don't care what to take, since each of them will melt into one steel ingot.
What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers p and f (1 ≤ p, f ≤ 10^9) — yours and your follower's capacities.
The second line of each test case contains two integers cnt_s and cnt_w (1 ≤ cnt_s, cnt_w ≤ 2 ⋅ 10^5) — the number of swords and war axes in the shop.
The third line of each test case contains two integers s and w (1 ≤ s, w ≤ 10^9) — the weights of each sword and each war axe.
It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.
Example
Input
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
Output
11
20
3
Note
In the first test case:
* you should take 3 swords and 3 war axes: 3 ⋅ 5 + 3 ⋅ 6 = 33 ≤ 33
* and your follower — 3 swords and 2 war axes: 3 ⋅ 5 + 2 ⋅ 6 = 27 ≤ 27.
3 + 3 + 3 + 2 = 11 weapons in total.
In the second test case, you can take all available weapons even without your follower's help, since 5 ⋅ 10 + 5 ⋅ 10 ≤ 100.
In the third test case, you can't take anything, but your follower can take 3 war axes: 3 ⋅ 5 ≤ 19. | instruction | 0 | 66,623 | 2 | 133,246 |
Tags: brute force, greedy, math
Correct Solution:
```
"""
Code of Ayush Tiwari
Codeforces: servermonk
Codechef: ayush572000
"""
import sys
input = sys.stdin.buffer.readline
def solution():
# This is the main code
p,f=map(int,input().split())
cnts,cntw=map(int,input().split())
s,w=map(int,input().split())
num1=0
num2=0
ans=0
for i in range(cnts+1):
num1=i
if i*s>p:
continue
x=p-i*s
num2=min(cntw,x//w)
x=num2*w
num1x=min(f//s,cnts-num1)
num2x=num1x*s
num1y=min(f//w,cntw-num2)
num2y=num1y*w
num1yy=min((f-num2y)//s,cnts-num1)
# print(num1)
num1xx=min((f-num2x)//w,cntw-num2)
z=max(num1x+num1xx,num1y+num1yy)
ans=max(ans,num1+num2+z)
print(ans)
t=int(input())
for _ in range(t):
solution()
``` | output | 1 | 66,623 | 2 | 133,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
In the blacksmith shop, you found cnt_s swords and cnt_w war axes. Each sword weights s units and each war axe — w units. You don't care what to take, since each of them will melt into one steel ingot.
What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers p and f (1 ≤ p, f ≤ 10^9) — yours and your follower's capacities.
The second line of each test case contains two integers cnt_s and cnt_w (1 ≤ cnt_s, cnt_w ≤ 2 ⋅ 10^5) — the number of swords and war axes in the shop.
The third line of each test case contains two integers s and w (1 ≤ s, w ≤ 10^9) — the weights of each sword and each war axe.
It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.
Example
Input
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
Output
11
20
3
Note
In the first test case:
* you should take 3 swords and 3 war axes: 3 ⋅ 5 + 3 ⋅ 6 = 33 ≤ 33
* and your follower — 3 swords and 2 war axes: 3 ⋅ 5 + 2 ⋅ 6 = 27 ≤ 27.
3 + 3 + 3 + 2 = 11 weapons in total.
In the second test case, you can take all available weapons even without your follower's help, since 5 ⋅ 10 + 5 ⋅ 10 ≤ 100.
In the third test case, you can't take anything, but your follower can take 3 war axes: 3 ⋅ 5 ≤ 19. | instruction | 0 | 66,624 | 2 | 133,248 |
Tags: brute force, greedy, math
Correct Solution:
```
t = int(input())
while(t):
t -= 1
p, f = map(int,input().split())
cs, cw = map(int,input().split())
s, w = map(int,input().split())
ans = 0
if s<w:
for s1 in range(min(p//s,cs)+1):
w1 = min((p-s1*s)//w,cw)
s2 = min(f//s,cs-s1)
w2 = min((f-s2*s)//w,cw-w1)
ans = max(ans,s1+s2+w1+w2)
else:
for w1 in range(min(p//w,cw)+1):
s1 = min((p-w1*w)//s,cs)
w2 = min(f//w,cw-w1)
s2 = min((f-w2*w)//s,cs-s1)
ans = max(ans,s1+s2+w1+w2)
print(ans)
``` | output | 1 | 66,624 | 2 | 133,249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.