lang
stringclasses 1
value | prompt
stringlengths 1.38k
11.3k
| eval_prompt
stringlengths 39
8.09k
| ground_truth
stringlengths 3
196
| unit_tests
stringlengths 44
873
| task_id
stringlengths 23
25
| split
stringclasses 2
values |
---|---|---|---|---|---|---|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a positive integer $$$n$$$. Let's call some positive integer $$$a$$$ without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express $$$n$$$ as a sum of positive palindromic integers. Two ways are considered different if the frequency of at least one palindromic integer is different in them. For example, $$$5=4+1$$$ and $$$5=3+1+1$$$ are considered different but $$$5=3+1+1$$$ and $$$5=1+3+1$$$ are considered the same. Formally, you need to find the number of distinct multisets of positive palindromic integers the sum of which is equal to $$$n$$$.Since the answer can be quite large, print it modulo $$$10^9+7$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$) denoting the number of testcases. Each testcase contains a single line of input containing a single integer $$$n$$$ ($$$1\leq n\leq 4\cdot 10^4$$$)Β β the required sum of palindromic integers.
Output Specification: For each testcase, print a single integer denoting the required answer modulo $$$10^9+7$$$.
Notes: NoteFor the first testcase, there are $$$7$$$ ways to partition $$$5$$$ as a sum of positive palindromic integers: $$$5=1+1+1+1+1$$$ $$$5=1+1+1+2$$$ $$$5=1+2+2$$$ $$$5=1+1+3$$$ $$$5=2+3$$$ $$$5=1+4$$$ $$$5=5$$$ For the second testcase, there are total $$$77$$$ ways to partition $$$12$$$ as a sum of positive integers but among them, the partitions $$$12=2+10$$$, $$$12=1+1+10$$$ and $$$12=12$$$ are not valid partitions of $$$12$$$ as a sum of positive palindromic integers because $$$10$$$ and $$$12$$$ are not palindromic. So, there are $$$74$$$ ways to partition $$$12$$$ as a sum of positive palindromic integers.
Code:
import sys
input = sys.stdin.readline
s = []
c = [1]
for y in range(1,40005):
if str(y) == (str(y))[::-1]:
s.append(y)
c.append(0)
for i in s:
for j in range(1,40005):
if j >= i:
# TODO: Your code here
a = int(input())
for y in range(a):
b = int(input())
print(c[b] % ((10 ** 9) + 7))
|
import sys
input = sys.stdin.readline
s = []
c = [1]
for y in range(1,40005):
if str(y) == (str(y))[::-1]:
s.append(y)
c.append(0)
for i in s:
for j in range(1,40005):
if j >= i:
{{completion}}
a = int(input())
for y in range(a):
b = int(input())
print(c[b] % ((10 ** 9) + 7))
|
c[j] += (c[j - i]) % ((10 ** 9) + 7)
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004786
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's say Pak Chanek has an array $$$A$$$ consisting of $$$N$$$ positive integers. Pak Chanek will do a number of operations. In each operation, Pak Chanek will do the following: Choose an index $$$p$$$ ($$$1 \leq p \leq N$$$). Let $$$c$$$ be the number of operations that have been done on index $$$p$$$ before this operation. Decrease the value of $$$A_p$$$ by $$$2^c$$$. Multiply the value of $$$A_p$$$ by $$$2$$$. After each operation, all elements of $$$A$$$ must be positive integers.An array $$$A$$$ is said to be sortable if and only if Pak Chanek can do zero or more operations so that $$$A_1 < A_2 < A_3 < A_4 < \ldots < A_N$$$.Pak Chanek must find an array $$$A$$$ that is sortable with length $$$N$$$ such that $$$A_1 + A_2 + A_3 + A_4 + \ldots + A_N$$$ is the minimum possible. If there are more than one possibilities, Pak Chanek must choose the array that is lexicographically minimum among them.Pak Chanek must solve the following things: Pak Chanek must print the value of $$$A_1 + A_2 + A_3 + A_4 + \ldots + A_N$$$ for that array. $$$Q$$$ questions will be given. For the $$$i$$$-th question, an integer $$$P_i$$$ is given. Pak Chanek must print the value of $$$A_{P_i}$$$. Help Pak Chanek solve the problem.Note: an array $$$B$$$ of size $$$N$$$ is said to be lexicographically smaller than an array $$$C$$$ that is also of size $$$N$$$ if and only if there exists an index $$$i$$$ such that $$$B_i < C_i$$$ and for each $$$j < i$$$, $$$B_j = C_j$$$.
Input Specification: The first line contains two integers $$$N$$$ and $$$Q$$$ ($$$1 \leq N \leq 10^9$$$, $$$0 \leq Q \leq \min(N, 10^5)$$$) β the required length of array $$$A$$$ and the number of questions. The $$$i$$$-th of the next $$$Q$$$ lines contains a single integer $$$P_i$$$ ($$$1 \leq P_1 < P_2 < \ldots < P_Q \leq N$$$) β the index asked in the $$$i$$$-th question.
Output Specification: Print $$$Q+1$$$ lines. The $$$1$$$-st line contains an integer representing $$$A_1 + A_2 + A_3 + A_4 + \ldots + A_N$$$. For each $$$1 \leq i \leq Q$$$, the $$$(i+1)$$$-th line contains an integer representing $$$A_{P_i}$$$.
Notes: NoteIn the first example, the array $$$A$$$ obtained is $$$[1, 2, 3, 3, 4, 4]$$$. We can see that the array is sortable by doing the following operations: Choose index $$$5$$$, then $$$A = [1, 2, 3, 3, 6, 4]$$$. Choose index $$$6$$$, then $$$A = [1, 2, 3, 3, 6, 6]$$$. Choose index $$$4$$$, then $$$A = [1, 2, 3, 4, 6, 6]$$$. Choose index $$$6$$$, then $$$A = [1, 2, 3, 4, 6, 8]$$$.
Code:
def ev(x):
k = 0
while x%2 == 0:
x//=2
k+=1
return x+k
p,q = [int(i) for i in input().split()]
t = 1
s = 1
sum = 0
while True:
ss = s + (t+1)//2
if ss > p:
m = (p-s+1)
sum += m*t
break
sum += t*((t+1)//2)
s = ss
t += 1
mx = t-2*m+1
print(sum)
tt = t
mul = 0
ded = 0
turn = 0
tt -= 0 if mx==turn else 1
for i in range(q):
x = int(input())
if x == 1:
print(1)
continue
while True:
#print("A:",turn,tt,x-ded)
if # TODO: Your code here:
print(ev(x-ded)+mul)
break
#print("WUT")
if tt < 0:
print(ev(x-ded)+mul)
break
ded += (tt+1)//2
turn+=1
mul += 1
tt -= 0 if mx==turn else 1
|
def ev(x):
k = 0
while x%2 == 0:
x//=2
k+=1
return x+k
p,q = [int(i) for i in input().split()]
t = 1
s = 1
sum = 0
while True:
ss = s + (t+1)//2
if ss > p:
m = (p-s+1)
sum += m*t
break
sum += t*((t+1)//2)
s = ss
t += 1
mx = t-2*m+1
print(sum)
tt = t
mul = 0
ded = 0
turn = 0
tt -= 0 if mx==turn else 1
for i in range(q):
x = int(input())
if x == 1:
print(1)
continue
while True:
#print("A:",turn,tt,x-ded)
if {{completion}}:
print(ev(x-ded)+mul)
break
#print("WUT")
if tt < 0:
print(ev(x-ded)+mul)
break
ded += (tt+1)//2
turn+=1
mul += 1
tt -= 0 if mx==turn else 1
|
x-ded <= tt
|
[{"input": "6 3\n1\n4\n5", "output": ["17\n1\n3\n4"]}, {"input": "1 0", "output": ["1"]}]
|
control_completion_003692
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array $$$[1, 1, 1]$$$ is $$$1$$$; $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$; $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.
Input Specification: In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).
Output Specification: Print the answer to each query on a new line.
Notes: NoteAfter the first query $$$a$$$ is equal to $$$[1, 2, 2, 4, 5]$$$, and the answer is $$$29$$$ because we can split each of the subsegments the following way: $$$[1; 1]$$$: $$$[1]$$$, 1 block; $$$[1; 2]$$$: $$$[1] + [2]$$$, 2 blocks; $$$[1; 3]$$$: $$$[1] + [2, 2]$$$, 2 blocks; $$$[1; 4]$$$: $$$[1] + [2, 2] + [4]$$$, 3 blocks; $$$[1; 5]$$$: $$$[1] + [2, 2] + [4] + [5]$$$, 4 blocks; $$$[2; 2]$$$: $$$[2]$$$, 1 block; $$$[2; 3]$$$: $$$[2, 2]$$$, 1 block; $$$[2; 4]$$$: $$$[2, 2] + [4]$$$, 2 blocks; $$$[2; 5]$$$: $$$[2, 2] + [4] + [5]$$$, 3 blocks; $$$[3; 3]$$$: $$$[2]$$$, 1 block; $$$[3; 4]$$$: $$$[2] + [4]$$$, 2 blocks; $$$[3; 5]$$$: $$$[2] + [4] + [5]$$$, 3 blocks; $$$[4; 4]$$$: $$$[4]$$$, 1 block; $$$[4; 5]$$$: $$$[4] + [5]$$$, 2 blocks; $$$[5; 5]$$$: $$$[5]$$$, 1 block; which is $$$1 + 2 + 2 + 3 + 4 + 1 + 1 + 2 + 3 + 1 + 2 + 3 + 1 + 2 + 1 = 29$$$ in total.
Code:
import sys
import collections
inf=float('inf')
mod=10**5+7
input = lambda: sys.stdin.readline().rstrip()
inpnm = lambda: map(int,input().split())
inparr = lambda: [int(i) for i in input().split()]
inpint = lambda: int(input())
# for case in range(inpint()):
n,m=inpnm()
arr=inparr()
res=[1]
cnt=0
se=1
t=1
for i in range(1,n):
if arr[i]==arr[i-1]:
cnt+=1
res.append(res[-1]+1)
else:
se+=1
t=res[-1]
res.append(res[-1]+se+cnt)
ans=sum(res)
for q in range(m):
i,x=inpnm()
i-=1
if i!=0 and arr[i-1]!=arr[i]:
ans-=i*(n-i)
if # TODO: Your code here:
ans-=(i+1)*(n-i-1)
arr[i]=x
if i!=0 and arr[i-1]!=x:
ans+=i*(n-i)
if i!=n-1 and arr[i+1]!=x:
ans+=(i+1)*(n-i-1)
print(ans)
|
import sys
import collections
inf=float('inf')
mod=10**5+7
input = lambda: sys.stdin.readline().rstrip()
inpnm = lambda: map(int,input().split())
inparr = lambda: [int(i) for i in input().split()]
inpint = lambda: int(input())
# for case in range(inpint()):
n,m=inpnm()
arr=inparr()
res=[1]
cnt=0
se=1
t=1
for i in range(1,n):
if arr[i]==arr[i-1]:
cnt+=1
res.append(res[-1]+1)
else:
se+=1
t=res[-1]
res.append(res[-1]+se+cnt)
ans=sum(res)
for q in range(m):
i,x=inpnm()
i-=1
if i!=0 and arr[i-1]!=arr[i]:
ans-=i*(n-i)
if {{completion}}:
ans-=(i+1)*(n-i-1)
arr[i]=x
if i!=0 and arr[i-1]!=x:
ans+=i*(n-i)
if i!=n-1 and arr[i+1]!=x:
ans+=(i+1)*(n-i-1)
print(ans)
|
i!=n-1 and arr[i+1]!=arr[i]
|
[{"input": "5 5\n1 2 3 4 5\n3 2\n4 2\n3 1\n2 1\n2 2", "output": ["29\n23\n35\n25\n35"]}]
|
control_completion_000084
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a tree, consisting of $$$n$$$ vertices. Each edge has an integer value written on it.Let $$$f(v, u)$$$ be the number of values that appear exactly once on the edges of a simple path between vertices $$$v$$$ and $$$u$$$.Calculate the sum of $$$f(v, u)$$$ over all pairs of vertices $$$v$$$ and $$$u$$$ such that $$$1 \le v < u \le n$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^5$$$)Β β the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains three integers $$$v, u$$$ and $$$x$$$ ($$$1 \le v, u, x \le n$$$)Β β the description of an edge: the vertices it connects and the value written on it. The given edges form a tree.
Output Specification: Print a single integerΒ β the sum of $$$f(v, u)$$$ over all pairs of vertices $$$v$$$ and $$$u$$$ such that $$$v < u$$$.
Code:
##########################
def tree_search(n,G,s,func1,func2,func3):
seen = [0] * (n + 1) # ε ΄εγ«γγ£γ¦γ―ε€γ«εΊγ
ind = [0] * (n + 1) ##
search=[s]
while search:
now=search[-1]
if seen[now]==0 and func1!=0:func1(now)
seen[now]=1
if len(G[now])>ind[now]:
next=G[now][ind[now]]
ind[now]+=1
if seen[next]>0:continue
if func2!=0:func2(now,next)
search.append(next)
else:
if # TODO: Your code here:func3(now)
search.pop()
#############################
import sys
input=sys.stdin.readline #ζεεε
₯εγ―γγγͺοΌοΌ
n=int(input())
root=[[] for i in range(n+3)]
col=dict()
e=[]
from _collections import defaultdict
for i in range(n-1):
a,b,x=map(int,input().split())
root[a].append(b)
root[b].append(a)
col[a,b]=x
col[b,a]=x
e.append((a,b,x))
def cnb(n):
return n*(n-1)//2
p=[0]*(n+2)
num=[0]*(n+3)
dp=[defaultdict(int) for i in range(n+3)]
omomi=defaultdict(int)
def f2(x,y):
p[y]=x
def f3(x):
num[x]=1
for y in root[x]:
if y==p[x]:continue
num[x]+=num[y]
for y in root[x]:
if y==p[x]:continue
if len(dp[x])<len(dp[y]):
res=dp[y]
for ke in dp[x]:res[ke]+=dp[x][ke]
else:
res = dp[x]
for ke in dp[y]: res[ke] += dp[y][ke]
dp[x] = res
if x>1:
c=col[x,p[x]]
omomi[x,c]=num[x]-dp[x][c]
dp[x][c]=num[x]
else:
for c in range(1,n+1):
omomi[1,c]=num[1]-dp[1][c]
tree_search(n,root,1,0,f2,f3)
nextp=[10**10]*(n+2)
nextc=[1]*(n+1)
ch=[]
def dfs(n,G,s):
seen = [0] * (n + 1) # ε ΄εγ«γγ£γ¦γ―ε€γ«εΊγ
ind = [0] * (n + 1) ##
search=[s]
while search:
now=search[-1]
seen[now]=1
if len(G[now])>ind[now]:
next=G[now][ind[now]]
ind[now]+=1
if seen[next]>0:continue
c=col[now,next]
nextp[next]=nextc[c]
tmp = nextc[c]
nextc[c]=next
ch.append((c,tmp))
search.append(next)
else:
if ch:
c,tmp=ch.pop()
nextc[c]=tmp
search.pop()
#############################
dfs(n,root,1)
ans=0
for a,b,c in e:
if num[a]>num[b]:
a,b=b,a
ans+=omomi[a,c]*omomi[nextp[a],c]
print(ans)
|
##########################
def tree_search(n,G,s,func1,func2,func3):
seen = [0] * (n + 1) # ε ΄εγ«γγ£γ¦γ―ε€γ«εΊγ
ind = [0] * (n + 1) ##
search=[s]
while search:
now=search[-1]
if seen[now]==0 and func1!=0:func1(now)
seen[now]=1
if len(G[now])>ind[now]:
next=G[now][ind[now]]
ind[now]+=1
if seen[next]>0:continue
if func2!=0:func2(now,next)
search.append(next)
else:
if {{completion}}:func3(now)
search.pop()
#############################
import sys
input=sys.stdin.readline #ζεεε
₯εγ―γγγͺοΌοΌ
n=int(input())
root=[[] for i in range(n+3)]
col=dict()
e=[]
from _collections import defaultdict
for i in range(n-1):
a,b,x=map(int,input().split())
root[a].append(b)
root[b].append(a)
col[a,b]=x
col[b,a]=x
e.append((a,b,x))
def cnb(n):
return n*(n-1)//2
p=[0]*(n+2)
num=[0]*(n+3)
dp=[defaultdict(int) for i in range(n+3)]
omomi=defaultdict(int)
def f2(x,y):
p[y]=x
def f3(x):
num[x]=1
for y in root[x]:
if y==p[x]:continue
num[x]+=num[y]
for y in root[x]:
if y==p[x]:continue
if len(dp[x])<len(dp[y]):
res=dp[y]
for ke in dp[x]:res[ke]+=dp[x][ke]
else:
res = dp[x]
for ke in dp[y]: res[ke] += dp[y][ke]
dp[x] = res
if x>1:
c=col[x,p[x]]
omomi[x,c]=num[x]-dp[x][c]
dp[x][c]=num[x]
else:
for c in range(1,n+1):
omomi[1,c]=num[1]-dp[1][c]
tree_search(n,root,1,0,f2,f3)
nextp=[10**10]*(n+2)
nextc=[1]*(n+1)
ch=[]
def dfs(n,G,s):
seen = [0] * (n + 1) # ε ΄εγ«γγ£γ¦γ―ε€γ«εΊγ
ind = [0] * (n + 1) ##
search=[s]
while search:
now=search[-1]
seen[now]=1
if len(G[now])>ind[now]:
next=G[now][ind[now]]
ind[now]+=1
if seen[next]>0:continue
c=col[now,next]
nextp[next]=nextc[c]
tmp = nextc[c]
nextc[c]=next
ch.append((c,tmp))
search.append(next)
else:
if ch:
c,tmp=ch.pop()
nextc[c]=tmp
search.pop()
#############################
dfs(n,root,1)
ans=0
for a,b,c in e:
if num[a]>num[b]:
a,b=b,a
ans+=omomi[a,c]*omomi[nextp[a],c]
print(ans)
|
func3!=0
|
[{"input": "3\n1 2 1\n1 3 2", "output": ["4"]}, {"input": "3\n1 2 2\n1 3 2", "output": ["2"]}, {"input": "5\n1 4 4\n1 2 3\n3 4 4\n4 5 5", "output": ["14"]}, {"input": "2\n2 1 1", "output": ["1"]}, {"input": "10\n10 2 3\n3 8 8\n4 8 9\n5 8 5\n3 10 7\n7 8 2\n5 6 6\n9 3 4\n1 6 3", "output": ["120"]}]
|
control_completion_001877
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can: Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.
Input Specification: The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) β the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).
Output Specification: For each test case, print one integer β the minimum number of days required to water the trees, so they grow to the same height.
Notes: NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$. During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$; during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.
Code:
# by the authority of GOD author: Kritarth Sharma #
import sys
from collections import defaultdict,deque,Counter
from bisect import bisect_left
import math
input=sys.stdin.readline
def inp():
l=list(map(int,input().split()))
return l
for _ in range(int(input())):
n,=inp()
l=inp()
m=max(l)
a=float('inf')
for i in range(m,m+2):
x=0
y=0
for j in range(n):
# TODO: Your code here
a=min(a,max( 2*y -1, ((2*x+y)//3)*2 +((2*x+y)%3) ))
print(a)
|
# by the authority of GOD author: Kritarth Sharma #
import sys
from collections import defaultdict,deque,Counter
from bisect import bisect_left
import math
input=sys.stdin.readline
def inp():
l=list(map(int,input().split()))
return l
for _ in range(int(input())):
n,=inp()
l=inp()
m=max(l)
a=float('inf')
for i in range(m,m+2):
x=0
y=0
for j in range(n):
{{completion}}
a=min(a,max( 2*y -1, ((2*x+y)//3)*2 +((2*x+y)%3) ))
print(a)
|
x+=(i-l[j])//2
y+=(i-l[j])%2
|
[{"input": "3\n3\n1 2 4\n5\n4 4 3 5 5\n7\n2 5 4 8 3 7 4", "output": ["4\n3\n16"]}]
|
block_completion_003423
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer β the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
for i in range(int(input())):
n= int(input())
a = dict()
b = dict()
c = dict()
ans = 0
for j in range(n):
d,e = str(input())
try:
ans += a[d]
a[d] += 1
except KeyError:
a[d] = 1
try:
ans += b[e]
b[e] += 1
except KeyError:
# TODO: Your code here
if d+e not in c:
c[d+e] = 0
else:
ans -= c[d+e]
c[d+e] += 2
print(ans)
|
for i in range(int(input())):
n= int(input())
a = dict()
b = dict()
c = dict()
ans = 0
for j in range(n):
d,e = str(input())
try:
ans += a[d]
a[d] += 1
except KeyError:
a[d] = 1
try:
ans += b[e]
b[e] += 1
except KeyError:
{{completion}}
if d+e not in c:
c[d+e] = 0
else:
ans -= c[d+e]
c[d+e] += 2
print(ans)
|
b[e] = 1
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
block_completion_000892
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a string $$$s$$$ consisting of $$$n$$$ characters. Each character of $$$s$$$ is either 0 or 1.A substring of $$$s$$$ is a contiguous subsequence of its characters.You have to choose two substrings of $$$s$$$ (possibly intersecting, possibly the same, possibly non-intersecting β just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows: let $$$s_1$$$ be the first substring, $$$s_2$$$ be the second chosen substring, and $$$f(s_i)$$$ be the integer such that $$$s_i$$$ is its binary representation (for example, if $$$s_i$$$ is 11010, $$$f(s_i) = 26$$$); the value is the bitwise OR of $$$f(s_1)$$$ and $$$f(s_2)$$$. Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.
Input Specification: The first line contains one integer $$$n$$$ β the number of characters in $$$s$$$. The second line contains $$$s$$$ itself, consisting of exactly $$$n$$$ characters 0 and/or 1. All non-example tests in this problem are generated randomly: every character of $$$s$$$ is chosen independently of other characters; for each character, the probability of it being 1 is exactly $$$\frac{1}{2}$$$. This problem has exactly $$$40$$$ tests. Tests from $$$1$$$ to $$$3$$$ are the examples; tests from $$$4$$$ to $$$40$$$ are generated randomly. In tests from $$$4$$$ to $$$10$$$, $$$n = 5$$$; in tests from $$$11$$$ to $$$20$$$, $$$n = 1000$$$; in tests from $$$21$$$ to $$$40$$$, $$$n = 10^6$$$. Hacks are forbidden in this problem.
Output Specification: Print the maximum possible value you can get in binary representation without leading zeroes.
Notes: NoteIn the first example, you can choose the substrings 11010 and 101. $$$f(s_1) = 26$$$, $$$f(s_2) = 5$$$, their bitwise OR is $$$31$$$, and the binary representation of $$$31$$$ is 11111.In the second example, you can choose the substrings 1110010 and 11100.
Code:
def random(st):
n = 8
st = int(st, 2)
MAX = st
for t in range(n):
# TODO: Your code here
return bin(MAX)[2:]
N = input()
b = input()
print(random(b))
|
def random(st):
n = 8
st = int(st, 2)
MAX = st
for t in range(n):
{{completion}}
return bin(MAX)[2:]
N = input()
b = input()
print(random(b))
|
MAX = max((st >> t) | st, MAX)
|
[{"input": "5\n11010", "output": ["11111"]}, {"input": "7\n1110010", "output": ["1111110"]}, {"input": "4\n0000", "output": ["0"]}]
|
block_completion_002161
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
# TODO: Your code here
else:
k=(maxW/a/gcdAB-x1)/b
print(max(val[a*gcdAB*(x1+math.ceil(k)*b)],val[a*gcdAB*(x1+math.floor(k)*b)]))
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
{{completion}}
else:
k=(maxW/a/gcdAB-x1)/b
print(max(val[a*gcdAB*(x1+math.ceil(k)*b)],val[a*gcdAB*(x1+math.floor(k)*b)]))
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
print(val[a*gcdAB*(x1+kmin*b)])
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005537
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an integer $$$n$$$.Let's define $$$s(n)$$$ as the string "BAN" concatenated $$$n$$$ times. For example, $$$s(1)$$$ = "BAN", $$$s(3)$$$ = "BANBANBAN". Note that the length of the string $$$s(n)$$$ is equal to $$$3n$$$.Consider $$$s(n)$$$. You can perform the following operation on $$$s(n)$$$ any number of times (possibly zero): Select any two distinct indices $$$i$$$ and $$$j$$$ $$$(1 \leq i, j \leq 3n, i \ne j)$$$. Then, swap $$$s(n)_i$$$ and $$$s(n)_j$$$. You want the string "BAN" to not appear in $$$s(n)$$$ as a subsequence. What's the smallest number of operations you have to do to achieve this? Also, find one such shortest sequence of operations.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 100)$$$ Β β the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 100)$$$.
Output Specification: For each test case, in the first line output $$$m$$$ ($$$0 \le m \le 10^5$$$)Β β the minimum number of operations required. It's guaranteed that the objective is always achievable in at most $$$10^5$$$ operations under the constraints of the problem. Then, output $$$m$$$ lines. The $$$k$$$-th of these lines should contain two integers $$$i_k$$$, $$$j_k$$$ $$$(1\leq i_k, j_k \leq 3n, i_k \ne j_k)$$$ denoting that you want to swap characters at indices $$$i_k$$$ and $$$j_k$$$ at the $$$k$$$-th operation. After all $$$m$$$ operations, "BAN" must not appear in $$$s(n)$$$ as a subsequence. If there are multiple possible answers, output any.
Notes: NoteIn the first testcase, $$$s(1) = $$$ "BAN", we can swap $$$s(1)_1$$$ and $$$s(1)_2$$$, converting $$$s(1)$$$ to "ABN", which does not contain "BAN" as a subsequence.In the second testcase, $$$s(2) = $$$ "BANBAN", we can swap $$$s(2)_2$$$ and $$$s(2)_6$$$, converting $$$s(2)$$$ to "BNNBAA", which does not contain "BAN" as a subsequence.
Code:
# get testcase input
t = int(input())
result = ""
while t:
t -= 1
n = int(input())
aux = int(n/2 if n%2==0 else n/2+1)
if n == 1:
result += "1\n1 2\n"
continue
result += str(aux) + "\n"
for i in range(aux):
# TODO: Your code here
print(result[:-1])
|
# get testcase input
t = int(input())
result = ""
while t:
t -= 1
n = int(input())
aux = int(n/2 if n%2==0 else n/2+1)
if n == 1:
result += "1\n1 2\n"
continue
result += str(aux) + "\n"
for i in range(aux):
{{completion}}
print(result[:-1])
|
result += str(2+3*i) + ' ' + str(3+3*(n-i-1)) + "\n"
|
[{"input": "2\n1\n2", "output": ["1\n1 2\n1\n2 6"]}]
|
block_completion_001833
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $$$v$$$ (different from root) is the previous to $$$v$$$ vertex on the shortest path from the root to the vertex $$$v$$$. Children of the vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent.You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex $$$v$$$, if at least one child of $$$v$$$ is infected, you can spread the disease by infecting at most one other child of $$$v$$$ of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β β the number of the vertices in the given tree. The second line of each test case contains $$$n - 1$$$ integers $$$p_2, p_3, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ is the ancestor of the $$$i$$$-th vertex in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case you should output a single integerΒ β the minimal number of seconds needed to infect the whole tree.
Notes: NoteThe image depicts the tree from the first test case during each second.A vertex is black if it is not infected. A vertex is blue if it is infected by injection during the previous second. A vertex is green if it is infected by spreading during the previous second. A vertex is red if it is infected earlier than the previous second. Note that you are able to choose which vertices are infected by spreading and by injections.
Code:
from heapq import *
for _ in range(int(input())):
n = int(input())
pp = list(map(int, input().split()))
sibs = [[] for _ in range(n+1)]
for i,p in enumerate(pp, 2):
sibs[p].append(i)
child_infected = [False] * (n+1)
isibs = sorted(range(1, n+1), key=lambda x:len(sibs[x]), reverse=True)
remain = n
to_spread = []
for turn, isib in enumerate(isibs):
children = sibs[isib]
while # TODO: Your code here:
heappop(to_spread)
remain -= len(to_spread)
child_infected[isib] = True
heappush(to_spread, (len(children)+turn, isib))
remain -= 1
if remain <= 0:
break
print(turn+1)
|
from heapq import *
for _ in range(int(input())):
n = int(input())
pp = list(map(int, input().split()))
sibs = [[] for _ in range(n+1)]
for i,p in enumerate(pp, 2):
sibs[p].append(i)
child_infected = [False] * (n+1)
isibs = sorted(range(1, n+1), key=lambda x:len(sibs[x]), reverse=True)
remain = n
to_spread = []
for turn, isib in enumerate(isibs):
children = sibs[isib]
while {{completion}}:
heappop(to_spread)
remain -= len(to_spread)
child_infected[isib] = True
heappush(to_spread, (len(children)+turn, isib))
remain -= 1
if remain <= 0:
break
print(turn+1)
|
to_spread and to_spread[0][0] <= turn
|
[{"input": "5\n7\n1 1 1 2 2 4\n5\n5 5 1 4\n2\n1\n3\n3 1\n6\n1 1 1 1 1", "output": ["4\n4\n2\n3\n4"]}]
|
control_completion_004308
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) β the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$) Β β the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.
Notes: NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.
Code:
import sys,os,io
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = sys.stdin.readline
for _ in range (int(input())):
c = [int(i) for i in input().split()]
s = list(input().strip())
if s.count('A') != c[0] + c[2] + c[3] or s.count('B') != c[1] + c[2] + c[3]:
print("NO")
continue
n = len(s)
a = [[s[0]]]
for i in range (1,n):
if s[i]==s[i-1]:
a.append([s[i]])
else:
a[-1].append(s[i])
extra = 0
for i in a:
if len(i)%2:
c[ord(i[0]) - ord('A')] -= 1
extra += len(i)//2
a.sort(key = lambda x: len(x))
for i in a:
if len(i)%2==0:
cnt = len(i)//2
if cnt <= c[2 + ord(i[0])-ord('A')]:
c[2 + ord(i[0]) - ord('A')]-=cnt
else:
# TODO: Your code here
if min(c)<0 or extra < c[2]+c[3]:
print("NO")
else:
print("YES")
|
import sys,os,io
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = sys.stdin.readline
for _ in range (int(input())):
c = [int(i) for i in input().split()]
s = list(input().strip())
if s.count('A') != c[0] + c[2] + c[3] or s.count('B') != c[1] + c[2] + c[3]:
print("NO")
continue
n = len(s)
a = [[s[0]]]
for i in range (1,n):
if s[i]==s[i-1]:
a.append([s[i]])
else:
a[-1].append(s[i])
extra = 0
for i in a:
if len(i)%2:
c[ord(i[0]) - ord('A')] -= 1
extra += len(i)//2
a.sort(key = lambda x: len(x))
for i in a:
if len(i)%2==0:
cnt = len(i)//2
if cnt <= c[2 + ord(i[0])-ord('A')]:
c[2 + ord(i[0]) - ord('A')]-=cnt
else:
{{completion}}
if min(c)<0 or extra < c[2]+c[3]:
print("NO")
else:
print("YES")
|
extra += cnt - 1
|
[{"input": "8\n1 0 0 0\nB\n0 0 1 0\nAB\n1 1 0 1\nABAB\n1 0 1 1\nABAAB\n1 1 2 2\nBAABBABBAA\n1 1 2 3\nABABABBAABAB\n2 3 5 4\nAABAABBABAAABABBABBBABB\n1 3 3 10\nBBABABABABBBABABABABABABAABABA", "output": ["NO\nYES\nYES\nYES\nYES\nYES\nNO\nYES"]}]
|
block_completion_001214
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is the easy version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1'($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good?
Input Specification: The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$)Β β the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$)Β β the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print a single line with one integerΒ β the minimum number of operations to make $$$s$$$ good.
Notes: NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100".In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.
Code:
def func(s):
curr=s[0]
c=0
count=0
for i in s:
if i==curr:
c+=1
elif c%2==0:
# TODO: Your code here
else:
curr=i
c=2
count+=1
return count
for i in range(int(input())):
n=int(input())
print(func(input()))
|
def func(s):
curr=s[0]
c=0
count=0
for i in s:
if i==curr:
c+=1
elif c%2==0:
{{completion}}
else:
curr=i
c=2
count+=1
return count
for i in range(int(input())):
n=int(input())
print(func(input()))
|
c=1
curr=i
continue
|
[{"input": "5\n10\n1110011000\n8\n11001111\n2\n00\n2\n11\n6\n100110", "output": ["3\n0\n0\n0\n3"]}]
|
block_completion_008122
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$)Β β the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.
Output Specification: Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.
Code:
(n,m),(*a,),*r=(map(int,s.split())for s in open(0))
b=[[0],[0]]
for x in b:
for # TODO: Your code here:x+=x[-1]+max(0,u-v),
max=min
for s,t in r:l=b[s>t];print(l[t]-l[s])
|
(n,m),(*a,),*r=(map(int,s.split())for s in open(0))
b=[[0],[0]]
for x in b:
for {{completion}}:x+=x[-1]+max(0,u-v),
max=min
for s,t in r:l=b[s>t];print(l[t]-l[s])
|
u,v in zip([0]+a,a)
|
[{"input": "7 6\n10 8 9 6 8 12 7\n1 2\n1 7\n4 6\n7 1\n3 5\n4 2", "output": ["2\n10\n0\n7\n3\n1"]}]
|
control_completion_002895
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) β indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 10^5$$$)Β β number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) β the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) β indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
import sys
class LCA:
def __init__(self, g, root=0):
self.g = g
self.root = root
n = len(g)
self.logn = (n - 1).bit_length()
self.depth = [None] * n
self.parent = [[None] * self.logn for _ in range(n)]
self._dfs()
self._doubling()
def _dfs(self):
self.depth[self.root] = 0
stack = [self.root]
while stack:
u = stack.pop()
for v in self.g[u]:
if # TODO: Your code here:
self.depth[v] = self.depth[u] + 1
self.parent[v][0] = u
stack.append(v)
def _doubling(self):
for i in range(self.logn - 1):
for p in self.parent:
if p[i] is not None:
p[i + 1] = self.parent[p[i]][i]
def lca(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
d = self.depth[v] - self.depth[u]
for i in range(d.bit_length()):
if d >> i & 1:
v = self.parent[v][i]
if u == v:
return u
for i in reversed(range(self.logn)):
if (pu := self.parent[u][i]) != (pv := self.parent[v][i]):
u, v = pu, pv
return self.parent[u][i]
def query(lca):
k = int(sys.stdin.readline())
p = sorted(
(int(x) - 1 for x in sys.stdin.readline().split()),
key=lca.depth.__getitem__,
reverse=True,
)
branch = []
top = p[0]
for x in p[1:]:
if lca.lca(top, x) == x:
top = x
else:
branch.append(x)
if not branch:
return True
if lca.lca(branch[0], p[0]) != lca.lca(branch[0], top):
return False
for i in range(1, len(branch)):
if lca.lca(branch[i - 1], branch[i]) != branch[i]:
return False
return True
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = (int(x) - 1 for x in sys.stdin.readline().split())
g[u].append(v)
g[v].append(u)
lca = LCA(g)
for _ in range(int(input())):
print("YES" if query(lca) else "NO")
|
import sys
class LCA:
def __init__(self, g, root=0):
self.g = g
self.root = root
n = len(g)
self.logn = (n - 1).bit_length()
self.depth = [None] * n
self.parent = [[None] * self.logn for _ in range(n)]
self._dfs()
self._doubling()
def _dfs(self):
self.depth[self.root] = 0
stack = [self.root]
while stack:
u = stack.pop()
for v in self.g[u]:
if {{completion}}:
self.depth[v] = self.depth[u] + 1
self.parent[v][0] = u
stack.append(v)
def _doubling(self):
for i in range(self.logn - 1):
for p in self.parent:
if p[i] is not None:
p[i + 1] = self.parent[p[i]][i]
def lca(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
d = self.depth[v] - self.depth[u]
for i in range(d.bit_length()):
if d >> i & 1:
v = self.parent[v][i]
if u == v:
return u
for i in reversed(range(self.logn)):
if (pu := self.parent[u][i]) != (pv := self.parent[v][i]):
u, v = pu, pv
return self.parent[u][i]
def query(lca):
k = int(sys.stdin.readline())
p = sorted(
(int(x) - 1 for x in sys.stdin.readline().split()),
key=lca.depth.__getitem__,
reverse=True,
)
branch = []
top = p[0]
for x in p[1:]:
if lca.lca(top, x) == x:
top = x
else:
branch.append(x)
if not branch:
return True
if lca.lca(branch[0], p[0]) != lca.lca(branch[0], top):
return False
for i in range(1, len(branch)):
if lca.lca(branch[i - 1], branch[i]) != branch[i]:
return False
return True
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = (int(x) - 1 for x in sys.stdin.readline().split())
g[u].append(v)
g[v].append(u)
lca = LCA(g)
for _ in range(int(input())):
print("YES" if query(lca) else "NO")
|
self.depth[v] is None
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
control_completion_002245
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$)Β β the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.
Output Specification: Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.
Code:
n,m=map(int,input().split())
c=[int(i) for i in input().split()]
f=[0]*n
g=[0]*n
for i in range(1,n):
f[i]=f[i-1]+max(0,c[i-1]-c[i])
g[-i-1]=g[-i]+max(0,c[-i]-c[-i-1])
for i in range(m):
x,y=map(int,input().split())
if # TODO: Your code here:
print(f[y-1]-f[x-1])
else:
print(g[y-1]-g[x-1])
|
n,m=map(int,input().split())
c=[int(i) for i in input().split()]
f=[0]*n
g=[0]*n
for i in range(1,n):
f[i]=f[i-1]+max(0,c[i-1]-c[i])
g[-i-1]=g[-i]+max(0,c[-i]-c[-i-1])
for i in range(m):
x,y=map(int,input().split())
if {{completion}}:
print(f[y-1]-f[x-1])
else:
print(g[y-1]-g[x-1])
|
x<y
|
[{"input": "7 6\n10 8 9 6 8 12 7\n1 2\n1 7\n4 6\n7 1\n3 5\n4 2", "output": ["2\n10\n0\n7\n3\n1"]}]
|
control_completion_002891
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$Β β the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.
Input Specification: The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$)Β β elements of given array.
Output Specification: In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.
Notes: NoteIn the first example $$$3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24$$$. Number $$$24$$$ is divisible by $$$4! = 24$$$.In the second example $$$3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18$$$, is divisible by $$$3! = 6$$$.In the third example $$$7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!$$$. It is easy to prove that this number is not divisible by $$$8!$$$.
Code:
def factorial_divisibility(n, x, a: list):
a.sort()
a.reverse()
while True:
k = a[-1]
a.pop()
cnt = 1
while len(a) > 0 and k == a[-1]:
# TODO: Your code here
if cnt < k + 1:
return ('Yes' if k >= x else 'No' )
for i in range(cnt // (k + 1)):
a.append(k + 1)
for i in range(cnt % (k + 1)):
a.append(k)
n, x = tuple(map(int, input().split(' ')))
a = input().split(' ')
a = list(map(int, a))
print(factorial_divisibility(n, x, a))
|
def factorial_divisibility(n, x, a: list):
a.sort()
a.reverse()
while True:
k = a[-1]
a.pop()
cnt = 1
while len(a) > 0 and k == a[-1]:
{{completion}}
if cnt < k + 1:
return ('Yes' if k >= x else 'No' )
for i in range(cnt // (k + 1)):
a.append(k + 1)
for i in range(cnt % (k + 1)):
a.append(k)
n, x = tuple(map(int, input().split(' ')))
a = input().split(' ')
a = list(map(int, a))
print(factorial_divisibility(n, x, a))
|
cnt += 1
a.pop()
|
[{"input": "6 4\n3 2 2 2 3 3", "output": ["Yes"]}, {"input": "8 3\n3 2 2 2 2 2 1 1", "output": ["Yes"]}, {"input": "7 8\n7 7 7 7 7 7 7", "output": ["No"]}, {"input": "10 5\n4 3 2 1 4 3 2 4 3 4", "output": ["No"]}, {"input": "2 500000\n499999 499999", "output": ["No"]}]
|
block_completion_006091
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given $$$n$$$ points on the plane, the coordinates of the $$$i$$$-th point are $$$(x_i, y_i)$$$. No two points have the same coordinates.The distance between points $$$i$$$ and $$$j$$$ is defined as $$$d(i,j) = |x_i - x_j| + |y_i - y_j|$$$.For each point, you have to choose a color, represented by an integer from $$$1$$$ to $$$n$$$. For every ordered triple of different points $$$(a,b,c)$$$, the following constraints should be met: if $$$a$$$, $$$b$$$ and $$$c$$$ have the same color, then $$$d(a,b) = d(a,c) = d(b,c)$$$; if $$$a$$$ and $$$b$$$ have the same color, and the color of $$$c$$$ is different from the color of $$$a$$$, then $$$d(a,b) < d(a,c)$$$ and $$$d(a,b) < d(b,c)$$$. Calculate the number of different ways to choose the colors that meet these constraints.
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β the number of points. Then $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^8$$$). No two points have the same coordinates (i.βe. if $$$i \ne j$$$, then either $$$x_i \ne x_j$$$ or $$$y_i \ne y_j$$$).
Output Specification: Print one integerΒ β the number of ways to choose the colors for the points. Since it can be large, print it modulo $$$998244353$$$.
Notes: NoteIn the first test, the following ways to choose the colors are suitable: $$$[1, 1, 1]$$$; $$$[2, 2, 2]$$$; $$$[3, 3, 3]$$$; $$$[1, 2, 3]$$$; $$$[1, 3, 2]$$$; $$$[2, 1, 3]$$$; $$$[2, 3, 1]$$$; $$$[3, 1, 2]$$$; $$$[3, 2, 1]$$$.
Code:
#############################
#############
cnb_max=10**5
mod=998244353
#############
kai=[1]*(cnb_max+1)
rkai=[1]*(cnb_max+1)
for i in range(cnb_max):
kai[i+1]=kai[i]*(i+1)%mod
rkai[cnb_max]=pow(kai[cnb_max],mod-2,mod)
for i in range(cnb_max):
rkai[cnb_max-1-i]=rkai[cnb_max-i]*(cnb_max-i)%mod
def cnb(x,y):
if y>x:
return 0
if x<0:return 0
if y<0:return 0
return (kai[x]*rkai[y]%mod)*rkai[x-y]%mod
def inv(n):
return kai[n-1]*rkai[n]%mod
##################################
n=int(input())
x=[]
y=[]
for i in range(n):
a,b=map(int,input().split())
x.append(a)
y.append(b)
ok=[[0]*n for i in range(n)]
tto=[0]*n
def dist(i,j):
return abs(x[i]-x[j])+abs(y[i]-y[j])
for i in range(n):
mi=10**18
for j in range(n):
if i==j:continue
mi=min(mi,dist(i,j))
for j in range(n):
if i==j:continue
if mi==dist(i,j):
ok[i][j]=1
tto[i]+=1
s=[]
for a in range(n):
for b in range(a+1,n):
for c in range(b+1,n):
for d in range(c+1,n):
nod=[a,b,c,d]
flag=1
for i in nod:
for j in nod:
if i==j:continue
flag&=ok[i][j]
if tto[i]!=3:# TODO: Your code here
if flag:s.append(4)
for a in range(n):
for b in range(a+1,n):
for c in range(b+1,n):
nod=[a,b,c]
flag=1
for i in nod:
for j in nod:
if i==j:continue
flag&=ok[i][j]
if tto[i]!=2:flag=0
if flag:s.append(3)
for a in range(n):
for b in range(a+1,n):
nod=[a,b]
flag=1
for i in nod:
for j in nod:
if i==j:continue
flag&=ok[i][j]
if tto[i]!=1:flag=0
if flag:s.append(2)
dp=[0]*(n+1)
dp[n-sum(s)]=1
for cnt in s:
newdp=[0]*(n+1)
for i in range(n+1):
dp[i]%=mod
if i+cnt<=n:newdp[i+cnt]+=dp[i]
if i+1<=n:newdp[i+1]+=dp[i]
dp=newdp[:]
ans=0
for k in range(n+1):
ans+=dp[k]*cnb(n,k)*kai[k]
ans%=mod
print(ans)
|
#############################
#############
cnb_max=10**5
mod=998244353
#############
kai=[1]*(cnb_max+1)
rkai=[1]*(cnb_max+1)
for i in range(cnb_max):
kai[i+1]=kai[i]*(i+1)%mod
rkai[cnb_max]=pow(kai[cnb_max],mod-2,mod)
for i in range(cnb_max):
rkai[cnb_max-1-i]=rkai[cnb_max-i]*(cnb_max-i)%mod
def cnb(x,y):
if y>x:
return 0
if x<0:return 0
if y<0:return 0
return (kai[x]*rkai[y]%mod)*rkai[x-y]%mod
def inv(n):
return kai[n-1]*rkai[n]%mod
##################################
n=int(input())
x=[]
y=[]
for i in range(n):
a,b=map(int,input().split())
x.append(a)
y.append(b)
ok=[[0]*n for i in range(n)]
tto=[0]*n
def dist(i,j):
return abs(x[i]-x[j])+abs(y[i]-y[j])
for i in range(n):
mi=10**18
for j in range(n):
if i==j:continue
mi=min(mi,dist(i,j))
for j in range(n):
if i==j:continue
if mi==dist(i,j):
ok[i][j]=1
tto[i]+=1
s=[]
for a in range(n):
for b in range(a+1,n):
for c in range(b+1,n):
for d in range(c+1,n):
nod=[a,b,c,d]
flag=1
for i in nod:
for j in nod:
if i==j:continue
flag&=ok[i][j]
if tto[i]!=3:{{completion}}
if flag:s.append(4)
for a in range(n):
for b in range(a+1,n):
for c in range(b+1,n):
nod=[a,b,c]
flag=1
for i in nod:
for j in nod:
if i==j:continue
flag&=ok[i][j]
if tto[i]!=2:flag=0
if flag:s.append(3)
for a in range(n):
for b in range(a+1,n):
nod=[a,b]
flag=1
for i in nod:
for j in nod:
if i==j:continue
flag&=ok[i][j]
if tto[i]!=1:flag=0
if flag:s.append(2)
dp=[0]*(n+1)
dp[n-sum(s)]=1
for cnt in s:
newdp=[0]*(n+1)
for i in range(n+1):
dp[i]%=mod
if i+cnt<=n:newdp[i+cnt]+=dp[i]
if i+1<=n:newdp[i+1]+=dp[i]
dp=newdp[:]
ans=0
for k in range(n+1):
ans+=dp[k]*cnb(n,k)*kai[k]
ans%=mod
print(ans)
|
flag=0
|
[{"input": "3\n1 0\n3 0\n2 1", "output": ["9"]}, {"input": "5\n1 2\n2 4\n3 4\n4 4\n1 3", "output": ["240"]}, {"input": "4\n1 0\n3 0\n2 1\n2 0", "output": ["24"]}]
|
block_completion_000548
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) Β β the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer Β β the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def cum_sum(nums):
curr = 0
result = [0]*len(nums)
for # TODO: Your code here:
curr += num
result[idx] = curr
return result
for i in range(1, len(lines), 2):
n, a, b = map(int, lines[i].split(" "))
nums = [0] + list(map(int, lines[i+1].split(" ")))
cumulative = cum_sum(nums)
smallest = float("inf")
for f in range(0, n+1):
curr = a*nums[f]+b*(cumulative[-1] - cumulative[f] - (n-f-1)*nums[f])
smallest = min(curr, smallest)
print(smallest)
|
import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def cum_sum(nums):
curr = 0
result = [0]*len(nums)
for {{completion}}:
curr += num
result[idx] = curr
return result
for i in range(1, len(lines), 2):
n, a, b = map(int, lines[i].split(" "))
nums = [0] + list(map(int, lines[i+1].split(" ")))
cumulative = cum_sum(nums)
smallest = float("inf")
for f in range(0, n+1):
curr = a*nums[f]+b*(cumulative[-1] - cumulative[f] - (n-f-1)*nums[f])
smallest = min(curr, smallest)
print(smallest)
|
idx, num in enumerate(nums)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008535
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
Input Specification: The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ Β β the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ Β β the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
Code:
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
tot = a[0]
for i in range(1, n):
if tot < 0:
break
elif tot == 0:
if a[i] != 0:
# TODO: Your code here
else:
tot += a[i]
else:
if tot == 0:
print("Yes")
continue
print("No")
|
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
tot = a[0]
for i in range(1, n):
if tot < 0:
break
elif tot == 0:
if a[i] != 0:
{{completion}}
else:
tot += a[i]
else:
if tot == 0:
print("Yes")
continue
print("No")
|
break
|
[{"input": "7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0", "output": ["No\nYes\nNo\nNo\nYes\nYes\nYes"]}]
|
block_completion_000424
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is the hard version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1' ($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good? Meanwhile, she also wants to know the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.
Input Specification: The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$)Β β the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$)Β β the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print a single line with two integersΒ β the minimum number of operations to make $$$s$$$ good, and the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.
Notes: NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively, the number of subsegments of it is $$$2$$$. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100", the number of subsegments of them are $$$2$$$, $$$4$$$, $$$4$$$ respectively. It's easy to find that the minimum number of subsegments among all solutions with the minimum number of operations is $$$2$$$.In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.
Code:
inp = [*open(0)]
for s in inp[2::2]:
s = s.strip()
res = 0
mseg = 1
prebit = None
for i in range(len(s) // 2):
if s[2*i] != s[2*i+1]:
res += 1
else:
if prebit is None:
prebit = s[2*i]
else:
# TODO: Your code here
print(res, mseg)
|
inp = [*open(0)]
for s in inp[2::2]:
s = s.strip()
res = 0
mseg = 1
prebit = None
for i in range(len(s) // 2):
if s[2*i] != s[2*i+1]:
res += 1
else:
if prebit is None:
prebit = s[2*i]
else:
{{completion}}
print(res, mseg)
|
mseg += 1 if s[2*i] != prebit else 0
prebit = s[2*i]
|
[{"input": "5\n10\n1110011000\n8\n11001111\n2\n00\n2\n11\n6\n100110", "output": ["3 2\n0 3\n0 1\n0 1\n3 1"]}]
|
block_completion_008094
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
print(val[a*gcdAB*(x1+kmin*b)])
else:
# TODO: Your code here
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
print(val[a*gcdAB*(x1+kmin*b)])
else:
{{completion}}
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
k=(maxW/a/gcdAB-x1)/b
print(max(val[a*gcdAB*(x1+math.ceil(k)*b)],val[a*gcdAB*(x1+math.floor(k)*b)]))
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005538
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$. Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) Β β the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) β the initial levels of trees moisture. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.
Output Specification: For each test case output a single integer β the minimum number of actions. It can be shown that the answer exists.
Notes: NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.
Code:
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
prefix = suffix = 0
for i in range(n - 1):
if (d := a[i] - a[i + 1]) > 0:
prefix += d
else:
# TODO: Your code here
print(abs(a[0] - prefix) + prefix + suffix)
|
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
prefix = suffix = 0
for i in range(n - 1):
if (d := a[i] - a[i + 1]) > 0:
prefix += d
else:
{{completion}}
print(abs(a[0] - prefix) + prefix + suffix)
|
suffix -= d
|
[{"input": "4\n3\n-2 -2 -2\n3\n10 4 7\n4\n4 -4 4 -4\n5\n1 -2 3 -4 5", "output": ["2\n13\n36\n33"]}]
|
block_completion_004197
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp plays "Rage of Empires II: Definitive Edition" β a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager β a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
Output Specification: Print one integer β the minimum number of onager shots needed to break at least two sections of the wall.
Notes: NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Code:
import math
n = int(input())
s = list(int(i) for i in input().split())
min1 = 10000000
for i in range(n-1):
a, b = (s[i], s[i+1]) if s[i] < s[i+1] else (s[i + 1], s[i])
if b > a * 2:
min1 = min(min1, math.ceil(b/2))
else:
# TODO: Your code here
for i in range(n-2):
a, b = ((s[i], s[i + 2]) if s[i] < s[i + 2] else (s[i + 2], s[i]))
min1 = min(min1, math.ceil(a // 2 + b // 2 + (0 if a % 2 == 0 and b % 2 == 0 else 1)))
min2 = math.ceil(min(s) / 2)
s.remove(min(s))
min3 = math.ceil(min(s) / 2)
min1 = min(min1, min2 + min3)
print(min1)
|
import math
n = int(input())
s = list(int(i) for i in input().split())
min1 = 10000000
for i in range(n-1):
a, b = (s[i], s[i+1]) if s[i] < s[i+1] else (s[i + 1], s[i])
if b > a * 2:
min1 = min(min1, math.ceil(b/2))
else:
{{completion}}
for i in range(n-2):
a, b = ((s[i], s[i + 2]) if s[i] < s[i + 2] else (s[i + 2], s[i]))
min1 = min(min1, math.ceil(a // 2 + b // 2 + (0 if a % 2 == 0 and b % 2 == 0 else 1)))
min2 = math.ceil(min(s) / 2)
s.remove(min(s))
min3 = math.ceil(min(s) / 2)
min1 = min(min1, min2 + min3)
print(min1)
|
min1 = min(min1, math.ceil((a + b) / 3))
|
[{"input": "5\n20 10 30 10 20", "output": ["10"]}, {"input": "3\n1 8 1", "output": ["1"]}, {"input": "6\n7 6 6 8 5 8", "output": ["4"]}, {"input": "6\n14 3 8 10 15 4", "output": ["4"]}, {"input": "4\n1 100 100 1", "output": ["2"]}, {"input": "3\n40 10 10", "output": ["7"]}]
|
block_completion_007911
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order: the root has index $$$1$$$; if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way: if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$; otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree: choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.
Output Specification: Print one integer β the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.
Code:
# trans rights
N = int(input())
N = 2 ** N
S = input()
U = [0] * N
cnt = 0
for i in range(N - 2, -1, -1):
a = 2 * i + 1
b = 2 * i + 2
if b >= N:
# TODO: Your code here
if U[a] != U[b]:
cnt += 1
U[i] = ord(S[i]) + 331 * min(U[a], U[b]) + 3331 * max(U[a], U[b]) + min(U[a], U[b]) ** 2
U[i] %= 2 ** 104
print(pow(2, cnt, 998244353))
|
# trans rights
N = int(input())
N = 2 ** N
S = input()
U = [0] * N
cnt = 0
for i in range(N - 2, -1, -1):
a = 2 * i + 1
b = 2 * i + 2
if b >= N:
{{completion}}
if U[a] != U[b]:
cnt += 1
U[i] = ord(S[i]) + 331 * min(U[a], U[b]) + 3331 * max(U[a], U[b]) + min(U[a], U[b]) ** 2
U[i] %= 2 ** 104
print(pow(2, cnt, 998244353))
|
U[i] = ord(S[i])
continue
|
[{"input": "4\nBAAAAAAAABBABAB", "output": ["16"]}, {"input": "2\nBAA", "output": ["1"]}, {"input": "2\nABA", "output": ["2"]}, {"input": "2\nAAB", "output": ["2"]}, {"input": "2\nAAA", "output": ["1"]}]
|
block_completion_001709
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a tree consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is equal to $$$a_i$$$.Recall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tree is good if no simple path has weight $$$0$$$.You can apply the following operation any number of times (possibly, zero): select a vertex of the tree and replace the value written on it with an arbitrary positive integer. What is the minimum number of times you have to apply this operation in order to make the tree good?
Input Specification: The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$)Β β the number of vertices. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i < 2^{30}$$$)Β β the numbers written on vertices. Then $$$n - 1$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n; x \ne y$$$) denoting an edge connecting vertex $$$x$$$ with vertex $$$y$$$. It is guaranteed that these edges form a tree.
Output Specification: Print a single integerΒ β the minimum number of times you have to apply the operation in order to make the tree good.
Notes: NoteIn the first example, it is enough to replace the value on the vertex $$$1$$$ with $$$13$$$, and the value on the vertex $$$4$$$ with $$$42$$$.
Code:
import sys
from types import GeneratorType
from collections import defaultdict
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if # TODO: Your code here:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
A = [int(x) for x in input().split()]
G = [[] for _ in range(N)]
for _ in range(N - 1):
x, y = [int(x) - 1 for x in input().split()]
G[x].append(y)
G[y].append(x)
B = [0] * N
vals = defaultdict(set)
res = [0]
@bootstrap
def fill_dfs(v, p):
B[v] = A[v]
if p != -1:
B[v] ^= B[p]
for u in G[v]:
if u != p:
yield fill_dfs(u, v)
yield
@bootstrap
def calc_dfs(v, p):
zero = False
vals[v].add(B[v])
for u in G[v]:
if u != p:
yield calc_dfs(u, v)
if len(vals[v]) < len(vals[u]):
vals[v], vals[u] = vals[u], vals[v]
for x in vals[u]:
zero |= (x ^ A[v]) in vals[v]
for x in vals[u]:
vals[v].add(x)
vals[u].clear()
if zero:
res[0] += 1
vals[v].clear()
yield
fill_dfs(0, -1)
calc_dfs(0, -1)
return res[0]
print(solve())
|
import sys
from types import GeneratorType
from collections import defaultdict
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if {{completion}}:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
A = [int(x) for x in input().split()]
G = [[] for _ in range(N)]
for _ in range(N - 1):
x, y = [int(x) - 1 for x in input().split()]
G[x].append(y)
G[y].append(x)
B = [0] * N
vals = defaultdict(set)
res = [0]
@bootstrap
def fill_dfs(v, p):
B[v] = A[v]
if p != -1:
B[v] ^= B[p]
for u in G[v]:
if u != p:
yield fill_dfs(u, v)
yield
@bootstrap
def calc_dfs(v, p):
zero = False
vals[v].add(B[v])
for u in G[v]:
if u != p:
yield calc_dfs(u, v)
if len(vals[v]) < len(vals[u]):
vals[v], vals[u] = vals[u], vals[v]
for x in vals[u]:
zero |= (x ^ A[v]) in vals[v]
for x in vals[u]:
vals[v].add(x)
vals[u].clear()
if zero:
res[0] += 1
vals[v].clear()
yield
fill_dfs(0, -1)
calc_dfs(0, -1)
return res[0]
print(solve())
|
type(to) is GeneratorType
|
[{"input": "6\n3 2 1 3 2 1\n4 5\n3 4\n1 4\n2 1\n6 1", "output": ["2"]}, {"input": "4\n2 1 1 1\n1 2\n1 3\n1 4", "output": ["0"]}, {"input": "5\n2 2 2 2 2\n1 2\n2 3\n3 4\n4 5", "output": ["2"]}]
|
control_completion_002988
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: This is the hard version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1' ($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good? Meanwhile, she also wants to know the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.
Input Specification: The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$)Β β the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$)Β β the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print a single line with two integersΒ β the minimum number of operations to make $$$s$$$ good, and the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.
Notes: NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively, the number of subsegments of it is $$$2$$$. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100", the number of subsegments of them are $$$2$$$, $$$4$$$, $$$4$$$ respectively. It's easy to find that the minimum number of subsegments among all solutions with the minimum number of operations is $$$2$$$.In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.
Code:
for _ in range(int(input())):
n = int(input())
l = [[], []]
for # TODO: Your code here:
l[x==y].append(int(x))
print(len(l[0]), sum(map(lambda x : x[0] ^ x[1], zip(l[1], l[1][1:]))) + 1)
|
for _ in range(int(input())):
n = int(input())
l = [[], []]
for {{completion}}:
l[x==y].append(int(x))
print(len(l[0]), sum(map(lambda x : x[0] ^ x[1], zip(l[1], l[1][1:]))) + 1)
|
x, y in zip(*[iter(input())]*2)
|
[{"input": "5\n10\n1110011000\n8\n11001111\n2\n00\n2\n11\n6\n100110", "output": ["3 2\n0 3\n0 1\n0 1\n3 1"]}]
|
control_completion_007953
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
from sys import stdin
t = int(input())
lines = stdin.read().split()
j = 0
for num in range(t):
for i in range(8):
if lines[i + j].count('R') == 8:
# TODO: Your code here
else:
print('B')
j += 8
|
from sys import stdin
t = int(input())
lines = stdin.read().split()
j = 0
for num in range(t):
for i in range(8):
if lines[i + j].count('R') == 8:
{{completion}}
else:
print('B')
j += 8
|
print('R')
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005809
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second β $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ β that is the number of seconds that we are guaranteed to cross the road, if the current color is r.
Input Specification: The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) β the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)β the length of the string $$$s$$$ and the current color of the traffic light. The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$. It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
Output Specification: For each test case output the minimal number of second in which you are guaranteed to cross the road.
Notes: NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.
Code:
from sys import stdin
from collections import deque
lst = stdin.read().split()
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
return inp()[0]
t = int(inp1())
for _ in range(t):
n = int(inp1())
c = inp1()
s = inp1()
ret = 0
l = []
last = ''
for i in range(n):
cur = s[i]
if cur == last:
continue
if cur == c:
last = cur
l.append((c, i))
elif cur == 'g':
# TODO: Your code here
first_g = -1
for i in range(len(l)):
if l[i][0] == 'g' and first_g != -1:
continue
elif l[i][0] == 'g' and first_g == -1:
first_g = l[i][1]
elif i == len(l) - 1:
ret = max(ret, n - l[i][1] + first_g)
else:
ret = max(ret, l[i + 1][1] - l[i][1])
print(ret)
|
from sys import stdin
from collections import deque
lst = stdin.read().split()
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
return inp()[0]
t = int(inp1())
for _ in range(t):
n = int(inp1())
c = inp1()
s = inp1()
ret = 0
l = []
last = ''
for i in range(n):
cur = s[i]
if cur == last:
continue
if cur == c:
last = cur
l.append((c, i))
elif cur == 'g':
{{completion}}
first_g = -1
for i in range(len(l)):
if l[i][0] == 'g' and first_g != -1:
continue
elif l[i][0] == 'g' and first_g == -1:
first_g = l[i][1]
elif i == len(l) - 1:
ret = max(ret, n - l[i][1] + first_g)
else:
ret = max(ret, l[i + 1][1] - l[i][1])
print(ret)
|
last = cur
l.append(('g', i))
|
[{"input": "6\n\n5 r\n\nrggry\n\n1 g\n\ng\n\n3 r\n\nrrg\n\n5 y\n\nyrrgy\n\n7 r\n\nrgrgyrg\n\n9 y\n\nrrrgyyygy", "output": ["3\n0\n2\n4\n1\n4"]}]
|
block_completion_004147
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import math
from collections import defaultdict, deque, Counter
from sys import stdin
inf = int(1e18)
input = stdin.readline
#fenwick Tree
#D V ARAVIND
def add(ft, i, v):
while i < len(ft):
ft[i] += v
i += i&(-i)
def get(ft, i):
s = 0
while (i > 0):
s = s + ft[i]
i = i - (i &(-i))
return(s)
for _ in range (1):
n,q = map(int, input().split())
ftr = [0 for i in range (n+1)]
ftc = [0 for i in range (n+1)]
visr = [0 for i in range (n+1)]
visc = [0 for i in range (n+1)]
for _ in range (q):
a = [int(i) for i in input().split()]
if a[0] == 1:
if visr[a[1]] == 0:
add(ftr, a[1], 1)
visr[a[1]] += 1
if visc[a[2]] == 0:
add(ftc, a[2], 1)
visc[a[2]] += 1
elif a[0] == 2:
if visr[a[1]] == 1:
add(ftr, a[1], -1)
visr[a[1]] -= 1
if visc[a[2]] == 1:
add(ftc, a[2], -1)
visc[a[2]] -= 1
else:
sr = get(ftr, a[3]) - get(ftr, a[1]-1)
sc = get(ftc, a[4]) - get(ftc, a[2]-1)
if (sr == a[3] - a[1] + 1) or (sc == a[4]-a[2]+1):
print("YES")
else:
# TODO: Your code here
|
import math
from collections import defaultdict, deque, Counter
from sys import stdin
inf = int(1e18)
input = stdin.readline
#fenwick Tree
#D V ARAVIND
def add(ft, i, v):
while i < len(ft):
ft[i] += v
i += i&(-i)
def get(ft, i):
s = 0
while (i > 0):
s = s + ft[i]
i = i - (i &(-i))
return(s)
for _ in range (1):
n,q = map(int, input().split())
ftr = [0 for i in range (n+1)]
ftc = [0 for i in range (n+1)]
visr = [0 for i in range (n+1)]
visc = [0 for i in range (n+1)]
for _ in range (q):
a = [int(i) for i in input().split()]
if a[0] == 1:
if visr[a[1]] == 0:
add(ftr, a[1], 1)
visr[a[1]] += 1
if visc[a[2]] == 0:
add(ftc, a[2], 1)
visc[a[2]] += 1
elif a[0] == 2:
if visr[a[1]] == 1:
add(ftr, a[1], -1)
visr[a[1]] -= 1
if visc[a[2]] == 1:
add(ftc, a[2], -1)
visc[a[2]] -= 1
else:
sr = get(ftr, a[3]) - get(ftr, a[1]-1)
sc = get(ftc, a[4]) - get(ftc, a[2]-1)
if (sr == a[3] - a[1] + 1) or (sc == a[4]-a[2]+1):
print("YES")
else:
{{completion}}
|
print("NO")
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005577
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
Input Specification: The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) β the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' β the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) β the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
Output Specification: Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
Code:
import sys
n, m, k = map(int, sys.stdin.readline().split())
board = [list(sys.stdin.readline().strip()) for _ in range(n)]
cnt = 0
for i in range(n):
for j in range(m):
cnt += board[i][j] == '*'
clean = 0
q, r = divmod(cnt, n)
for j in range(q):
for i in range(n):
clean += board[i][j] == '*'
for i in range(r):
clean += board[i][q] == '*'
for _ in range(k):
x, y = map(int, sys.stdin.readline().split())
x -= 1
y -= 1
if board[x][y] == '.':
board[x][y] = '*'
cnt += 1
q, r = divmod(cnt - 1, n)
if board[r][q] == '*':
clean += 1
if n * y + x <= cnt - 1:
clean += 1
if (q, r) == (y, x):
clean -= 1
else:
cnt -= 1
q, r = divmod(cnt, n)
if board[r][q] == '*':
clean -= 1
if n * y + x <= cnt - 1:
# TODO: Your code here
board[x][y] = '.'
print(cnt - clean)
|
import sys
n, m, k = map(int, sys.stdin.readline().split())
board = [list(sys.stdin.readline().strip()) for _ in range(n)]
cnt = 0
for i in range(n):
for j in range(m):
cnt += board[i][j] == '*'
clean = 0
q, r = divmod(cnt, n)
for j in range(q):
for i in range(n):
clean += board[i][j] == '*'
for i in range(r):
clean += board[i][q] == '*'
for _ in range(k):
x, y = map(int, sys.stdin.readline().split())
x -= 1
y -= 1
if board[x][y] == '.':
board[x][y] = '*'
cnt += 1
q, r = divmod(cnt - 1, n)
if board[r][q] == '*':
clean += 1
if n * y + x <= cnt - 1:
clean += 1
if (q, r) == (y, x):
clean -= 1
else:
cnt -= 1
q, r = divmod(cnt, n)
if board[r][q] == '*':
clean -= 1
if n * y + x <= cnt - 1:
{{completion}}
board[x][y] = '.'
print(cnt - clean)
|
clean -= 1
|
[{"input": "4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "output": ["3\n4\n4\n3\n4\n5\n5\n5"]}, {"input": "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3", "output": ["2\n3\n3\n3\n2"]}]
|
block_completion_007865
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) β indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 10^5$$$)Β β number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) β the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) β indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
from collections import defaultdict, deque, Counter
import sys
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce, lru_cache
from bisect import bisect_left, bisect_right
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')
inf = float('inf')
eps = 10 ** (-12)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
# lca
class Doubling():
def __init__(self, n, edges, root):
self.n = n
self.logn = n.bit_length()
self.doubling = [[-1] * self.n for _ in range(self.logn)]
self.depth = [-1] * N
self.depth[root] = 0
# bfs
par = [-1] * N
pos = deque([root])
while len(pos) > 0:
u = pos.popleft()
for v in edges[u]:
if # TODO: Your code here:
self.depth[v] = self.depth[u] + 1
par[v] = u
pos.append(v)
# doubling
for i in range(self.n):
self.doubling[0][i] = par[i]
for i in range(1, self.logn):
for j in range(self.n):
if self.doubling[i - 1][j] == -1:
self.doubling[i][j] = -1
else:
self.doubling[i][j] = self.doubling[i - 1][self.doubling[i - 1][j]]
def lca(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
du = self.depth[u]
dv = self.depth[v]
for i in range(self.logn):
if (dv - du) >> i & 1:
v = self.doubling[i][v]
if u == v: return u
for i in range(self.logn - 1, -1, -1):
pu, pv = self.doubling[i][u], self.doubling[i][v]
if pu != pv:
u, v = pu, pv
return self.doubling[0][u]
def upstream(self, s, t):
if t == 0:
return s
now = s
for k in range(self.logn):
if t & (1 << k):
now = self.doubling[k][now]
return now
N = getN()
E = [[] for i in range(N)]
for _ in range(N - 1):
a, b = getNM()
E[a - 1].append(b - 1)
E[b - 1].append(a - 1)
D = Doubling(N, E, 0)
Q = getN()
for _ in range(Q):
q_n = getN()
V = sorted([[D.depth[p], p] for p in getListGraph()])
p1 = V.pop()[1]
flag = True
while V:
p2 = V.pop()[1]
lca_p = D.lca(p1, p2)
if lca_p != p2:
while V:
opt_p = V.pop()[1]
# print(D.lca(p1, opt_p), (D.lca(p2, opt_p)))
if not (opt_p == lca_p or ((D.lca(p1, opt_p) == opt_p) ^ (D.lca(p2, opt_p) == opt_p))):
flag = False
print("YES" if flag else "NO")
|
from collections import defaultdict, deque, Counter
import sys
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce, lru_cache
from bisect import bisect_left, bisect_right
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')
inf = float('inf')
eps = 10 ** (-12)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
# lca
class Doubling():
def __init__(self, n, edges, root):
self.n = n
self.logn = n.bit_length()
self.doubling = [[-1] * self.n for _ in range(self.logn)]
self.depth = [-1] * N
self.depth[root] = 0
# bfs
par = [-1] * N
pos = deque([root])
while len(pos) > 0:
u = pos.popleft()
for v in edges[u]:
if {{completion}}:
self.depth[v] = self.depth[u] + 1
par[v] = u
pos.append(v)
# doubling
for i in range(self.n):
self.doubling[0][i] = par[i]
for i in range(1, self.logn):
for j in range(self.n):
if self.doubling[i - 1][j] == -1:
self.doubling[i][j] = -1
else:
self.doubling[i][j] = self.doubling[i - 1][self.doubling[i - 1][j]]
def lca(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
du = self.depth[u]
dv = self.depth[v]
for i in range(self.logn):
if (dv - du) >> i & 1:
v = self.doubling[i][v]
if u == v: return u
for i in range(self.logn - 1, -1, -1):
pu, pv = self.doubling[i][u], self.doubling[i][v]
if pu != pv:
u, v = pu, pv
return self.doubling[0][u]
def upstream(self, s, t):
if t == 0:
return s
now = s
for k in range(self.logn):
if t & (1 << k):
now = self.doubling[k][now]
return now
N = getN()
E = [[] for i in range(N)]
for _ in range(N - 1):
a, b = getNM()
E[a - 1].append(b - 1)
E[b - 1].append(a - 1)
D = Doubling(N, E, 0)
Q = getN()
for _ in range(Q):
q_n = getN()
V = sorted([[D.depth[p], p] for p in getListGraph()])
p1 = V.pop()[1]
flag = True
while V:
p2 = V.pop()[1]
lca_p = D.lca(p1, p2)
if lca_p != p2:
while V:
opt_p = V.pop()[1]
# print(D.lca(p1, opt_p), (D.lca(p2, opt_p)))
if not (opt_p == lca_p or ((D.lca(p1, opt_p) == opt_p) ^ (D.lca(p2, opt_p) == opt_p))):
flag = False
print("YES" if flag else "NO")
|
self.depth[v] == -1
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
control_completion_002239
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Recently in Divanovo, a huge river locks system was built. There are now $$$n$$$ locks, the $$$i$$$-th of them has the volume of $$$v_i$$$ liters, so that it can contain any amount of water between $$$0$$$ and $$$v_i$$$ liters. Each lock has a pipe attached to it. When the pipe is open, $$$1$$$ liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $$$i$$$ to the lock $$$i + 1$$$. If the lock $$$i + 1$$$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $$$5$$$ locks with two open pipes at locks $$$1$$$ and $$$3$$$. Because locks $$$1$$$, $$$3$$$, and $$$4$$$ are already filled, effectively the water goes to locks $$$2$$$ and $$$5$$$. Note that the volume of the $$$i$$$-th lock may be greater than the volume of the $$$i + 1$$$-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $$$q$$$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $$$j$$$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $$$t_j$$$ seconds.Please help the mayor to solve this tricky problem and answer his queries.
Input Specification: The first lines contains one integer $$$n$$$ ($$$1 \le n \le 200\,000$$$)Β β the number of locks. The second lines contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$1 \le v_i \le 10^9$$$))Β β volumes of the locks. The third line contains one integer $$$q$$$ ($$$1 \le q \le 200\,000$$$)Β β the number of queries. Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \le t_j \le 10^9$$$)Β β the number of seconds you have to fill all the locks in the query $$$j$$$.
Output Specification: Print $$$q$$$ integers. The $$$j$$$-th of them should be equal to the minimum number of pipes to turn on so that after $$$t_j$$$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $$$-1$$$.
Notes: NoteThere are $$$6$$$ queries in the first example test. In the queries $$$1, 3, 4$$$ the answer is $$$-1$$$. We need to wait $$$4$$$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$. After $$$4$$$ seconds the locks $$$1$$$ and $$$4$$$ are full. In the following $$$1$$$ second $$$1$$$ liter of water is transferred to the locks $$$2$$$ and $$$5$$$. The lock $$$3$$$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$.In the fifth query one can open pipes $$$1, 2, 3, 4$$$.
Code:
from math import ceil
r = range;i = lambda: int(input());s = lambda: input().split()
for _ in r(1):
n = i();v = list(map(int,s()))
dp = [];sum = 0;max = 0
for _ in r(n):
sum += v[_];val = ceil(sum/(_+1))
dp += val, #comma --> tuple element
if# TODO: Your code here: max = val
for _ in r(i()): t = i();print(ceil(sum/t)) if(max <= t) else print(-1)
|
from math import ceil
r = range;i = lambda: int(input());s = lambda: input().split()
for _ in r(1):
n = i();v = list(map(int,s()))
dp = [];sum = 0;max = 0
for _ in r(n):
sum += v[_];val = ceil(sum/(_+1))
dp += val, #comma --> tuple element
if{{completion}}: max = val
for _ in r(i()): t = i();print(ceil(sum/t)) if(max <= t) else print(-1)
|
(val > max)
|
[{"input": "5\n4 1 5 4 1\n6\n1\n6\n2\n3\n4\n5", "output": ["-1\n3\n-1\n-1\n4\n3"]}, {"input": "5\n4 4 4 4 4\n6\n1\n3\n6\n5\n2\n4", "output": ["-1\n-1\n4\n4\n-1\n5"]}]
|
control_completion_004186
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells: An empty cell, denoted with '.'. A stone, denoted with '*'. An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?
Input Specification: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$)Β β the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$)Β β the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o'Β β an empty cell, a stone, or an obstacle, respectively.
Output Specification: For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.
Code:
c=input()
for _ in range(int(c)):
b=input().split()
a=[]
for i in range(int(b[0])):
a.append(list(input()))
for i in range(int(b[1])):
count=0
row=int(b[0])-1
for j in range(int(b[0])):
if a[row][i]=='.':
count+=1
elif # TODO: Your code here:
count=0
else:
a[row][i],a[row+count][i]='.',a[row][i]
row-=1
for i in range(int(b[0])):
print("".join(a[i]))
|
c=input()
for _ in range(int(c)):
b=input().split()
a=[]
for i in range(int(b[0])):
a.append(list(input()))
for i in range(int(b[1])):
count=0
row=int(b[0])-1
for j in range(int(b[0])):
if a[row][i]=='.':
count+=1
elif {{completion}}:
count=0
else:
a[row][i],a[row+count][i]='.',a[row][i]
row-=1
for i in range(int(b[0])):
print("".join(a[i]))
|
a[row][i]=='o'
|
[{"input": "3\n6 10\n.*.*....*.\n.*.......*\n...o....o.\n.*.*....*.\n..........\n.o......o*\n2 9\n...***ooo\n.*o.*o.*o\n5 5\n*****\n*....\n*****\n....*\n*****", "output": ["..........\n...*....*.\n.*.o....o.\n.*........\n.*......**\n.o.*....o*\n\n....**ooo\n.*o**o.*o\n\n.....\n*...*\n*****\n*****\n*****"]}]
|
control_completion_000832
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) β indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 5$$$)Β β number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) β the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) β indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
from collections import deque
import sys
input = lambda: sys.stdin.readline().rstrip()
def solve():
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = [int(x) - 1 for x in input().split()]
G[u].append(v)
G[v].append(u)
# build a tree with BFS
par = [-1] * n
depth = [0] * n
q = deque([0])
while q:
u = q.popleft()
for v in G[u]:
if v != par[u]:
# TODO: Your code here
# Path to LCA
def build_path(u, v):
path = []
if depth[u] < depth[v]:
u, v = v, u
while depth[u] > depth[v]:
path.append(u)
u = par[u]
while u != v:
path.append(u)
path.append(v)
u, v = par[u], par[v]
path.append(u)
return path
res = []
q = int(input())
for _ in range(q):
k = int(input())
P = [int(x) - 1 for x in input().split()]
if k == 1:
res.append("YES")
continue
P.sort(key=lambda u: depth[u])
u = P.pop()
v = P.pop()
path = build_path(u, v)
while P and u == path[0] and v == path[-1]:
u = v
v = P.pop()
path = build_path(u, v)
ans = "YES"
for u in P:
if u not in path:
ans = "NO"
break
res.append(ans)
return res
res = solve()
print("\n".join(res))
|
from collections import deque
import sys
input = lambda: sys.stdin.readline().rstrip()
def solve():
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = [int(x) - 1 for x in input().split()]
G[u].append(v)
G[v].append(u)
# build a tree with BFS
par = [-1] * n
depth = [0] * n
q = deque([0])
while q:
u = q.popleft()
for v in G[u]:
if v != par[u]:
{{completion}}
# Path to LCA
def build_path(u, v):
path = []
if depth[u] < depth[v]:
u, v = v, u
while depth[u] > depth[v]:
path.append(u)
u = par[u]
while u != v:
path.append(u)
path.append(v)
u, v = par[u], par[v]
path.append(u)
return path
res = []
q = int(input())
for _ in range(q):
k = int(input())
P = [int(x) - 1 for x in input().split()]
if k == 1:
res.append("YES")
continue
P.sort(key=lambda u: depth[u])
u = P.pop()
v = P.pop()
path = build_path(u, v)
while P and u == path[0] and v == path[-1]:
u = v
v = P.pop()
path = build_path(u, v)
ans = "YES"
for u in P:
if u not in path:
ans = "NO"
break
res.append(ans)
return res
res = solve()
print("\n".join(res))
|
par[v] = u
depth[v] = depth[u] + 1
q.append(v)
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
block_completion_002261
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) β indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 5$$$)Β β number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) β the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) β indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
from collections import deque
n=I();adj=[[] for i in range(n)]
for i in range(n-1):
p,q=M()
adj[p-1].append(q-1)
adj[q-1].append(p-1)
p=[-1]*n;d=[0]*n
q=deque([0]);v=[0]*n
while q:
r=q.popleft()
v[r]=1
for j in adj[r]:
if v[j]==0:
q.append(j);d[j]=d[r]+1;p[j]=r
q=I()
for i in range(q):
k=I()
a=L();y=a[:]
f=0;z=[]
j=0;m=0;s=set()
for i in a:
if # TODO: Your code here:m=d[i-1];j=i-1
while j not in s:
s.add(j);z.append(j);j=p[j]
if j==-1:break
b=[]
for i in a:
if i-1 not in s:b.append(i)
a=b[:]
if len(a)==0:print("YES");continue
j=0;m=0;s1=set();x=0
for i in a:
if d[i-1]>m:m=d[i-1];j=i-1
while j not in s and p[j]!=-1:
s1.add(j);j=p[j]
for t in range(len(z)-1,-1,-1):
if z[t]==j:x=1
if x==1:s1.add(z[t])
for i in y:
if i-1 not in s1:f=1;break
print("NO" if f else "YES")
|
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
from collections import deque
n=I();adj=[[] for i in range(n)]
for i in range(n-1):
p,q=M()
adj[p-1].append(q-1)
adj[q-1].append(p-1)
p=[-1]*n;d=[0]*n
q=deque([0]);v=[0]*n
while q:
r=q.popleft()
v[r]=1
for j in adj[r]:
if v[j]==0:
q.append(j);d[j]=d[r]+1;p[j]=r
q=I()
for i in range(q):
k=I()
a=L();y=a[:]
f=0;z=[]
j=0;m=0;s=set()
for i in a:
if {{completion}}:m=d[i-1];j=i-1
while j not in s:
s.add(j);z.append(j);j=p[j]
if j==-1:break
b=[]
for i in a:
if i-1 not in s:b.append(i)
a=b[:]
if len(a)==0:print("YES");continue
j=0;m=0;s1=set();x=0
for i in a:
if d[i-1]>m:m=d[i-1];j=i-1
while j not in s and p[j]!=-1:
s1.add(j);j=p[j]
for t in range(len(z)-1,-1,-1):
if z[t]==j:x=1
if x==1:s1.add(z[t])
for i in y:
if i-1 not in s1:f=1;break
print("NO" if f else "YES")
|
d[i-1]>m
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
control_completion_002215
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: On a beach there are $$$n$$$ huts in a perfect line, hut $$$1$$$ being at the left and hut $$$i+1$$$ being $$$100$$$ meters to the right of hut $$$i$$$, for all $$$1 \le i \le n - 1$$$. In hut $$$i$$$ there are $$$p_i$$$ people.There are $$$m$$$ ice cream sellers, also aligned in a perfect line with all the huts. The $$$i$$$-th ice cream seller has their shop $$$x_i$$$ meters to the right of the first hut. All ice cream shops are at distinct locations, but they may be at the same location as a hut.You want to open a new ice cream shop and you wonder what the best location for your shop is. You can place your ice cream shop anywhere on the beach (not necessarily at an integer distance from the first hut) as long as it is aligned with the huts and the other ice cream shops, even if there is already another ice cream shop or a hut at that location. You know that people would come to your shop only if it is strictly closer to their hut than any other ice cream shop.If every person living in the huts wants to buy exactly one ice cream, what is the maximum number of ice creams that you can sell if you place the shop optimally?
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 200\,000$$$, $$$1 \le m \le 200\,000$$$) β the number of huts and the number of ice cream sellers. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le 10^9$$$) β the number of people in each hut. The third line contains $$$m$$$ integers $$$x_1, x_2, \ldots, x_m$$$ ($$$0 \le x_i \le 10^9$$$, $$$x_i \ne x_j$$$ for $$$i \ne j$$$) β the location of each ice cream shop.
Output Specification: Print the maximum number of ice creams that can be sold by choosing optimally the location of the new shop.
Notes: NoteIn the first sample, you can place the shop (coloured orange in the picture below) $$$150$$$ meters to the right of the first hut (for example) so that it is the closest shop to the first two huts, which have $$$2$$$ and $$$5$$$ people, for a total of $$$7$$$ sold ice creams. In the second sample, you can place the shop $$$170$$$ meters to the right of the first hut (for example) so that it is the closest shop to the last two huts, which have $$$7$$$ and $$$8$$$ people, for a total of $$$15$$$ sold ice creams.
Code:
n,m=map(int,input().split())
p=list(map(int,input().split()))
x=sorted(list(map(int,input().split())))
s=sum(p[:-(-(x[0])//100)])
for i in range(len(x)-1):
if x[i]//100+1>=n:
break
num=int(((x[i+1]-x[i])/2)//(100)+1)
l=x[i]//100+1
r=-(-(x[i+1])//100)
r=min(r,n)
prefs=0
if l+num<=r:
# TODO: Your code here
while l+num<r:
prefs-=p[l]
prefs+=p[l+num] if l+num<n else 0
s=max(s,prefs)
l+=1
s=max(s,sum(p[x[-1]//100+1:]))
print(s)
|
n,m=map(int,input().split())
p=list(map(int,input().split()))
x=sorted(list(map(int,input().split())))
s=sum(p[:-(-(x[0])//100)])
for i in range(len(x)-1):
if x[i]//100+1>=n:
break
num=int(((x[i+1]-x[i])/2)//(100)+1)
l=x[i]//100+1
r=-(-(x[i+1])//100)
r=min(r,n)
prefs=0
if l+num<=r:
{{completion}}
while l+num<r:
prefs-=p[l]
prefs+=p[l+num] if l+num<n else 0
s=max(s,prefs)
l+=1
s=max(s,sum(p[x[-1]//100+1:]))
print(s)
|
prefs=sum(p[l:l+num])
s=max(s,prefs)
|
[{"input": "3 1\n2 5 6\n169", "output": ["7"]}, {"input": "4 2\n1 2 7 8\n35 157", "output": ["15"]}, {"input": "4 1\n272203905 348354708 848256926 939404176\n20", "output": ["2136015810"]}, {"input": "3 2\n1 1 1\n300 99", "output": ["2"]}]
|
block_completion_001152
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if # TODO: Your code here:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
res += [1] * (j-i)
st = j
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if {{completion}}:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
res += [1] * (j-i)
st = j
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
word != 0
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
control_completion_005831
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ candies put from left to right on a table. The candies are numbered from left to right. The $$$i$$$-th candy has weight $$$w_i$$$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row). Of course, if Alice ate a candy, Bob can't eat it (and vice versa).They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)Β β the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$)Β β the number of candies on the table. The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \leq w_i \leq 10^4$$$)Β β the weights of candies from left to right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
Output Specification: For each test case, print a single integerΒ β the maximum number of candies Alice and Bob can eat in total while satisfying the condition.
Notes: NoteFor the first test case, Alice will eat one candy from the left and Bob will eat one candy from the right. There is no better way for them to eat the same total amount of weight. The answer is $$$2$$$ because they eat two candies in total.For the second test case, Alice will eat the first three candies from the left (with total weight $$$7$$$) and Bob will eat the first three candies from the right (with total weight $$$7$$$). They cannot eat more candies since all the candies have been eaten, so the answer is $$$6$$$ (because they eat six candies in total).For the third test case, there is no way Alice and Bob will eat the same non-zero weight so the answer is $$$0$$$.For the fourth test case, Alice will eat candies with weights $$$[7, 3, 20]$$$ and Bob will eat candies with weights $$$[10, 8, 11, 1]$$$, they each eat $$$30$$$ weight. There is no better partition so the answer is $$$7$$$.
Code:
def read():
return int(input())
def readline():
return list(map(int,input().split()))
def solve():
n=read()
arr=readline()
ans,cur=0,0
a,suma=-1,0
b,sumb=n,0
while True:
if a>=b: break
elif suma>sumb:
b-=1
sumb+=arr[b]
cur+=1
elif # TODO: Your code here:
a+=1
suma+=arr[a]
cur+=1
else :
ans=cur
a+=1
b-=1
suma+=arr[a]
sumb+=arr[b]
cur+=2
print(ans)
if __name__ == "__main__":
T=read()
for i in range(T):
solve()
|
def read():
return int(input())
def readline():
return list(map(int,input().split()))
def solve():
n=read()
arr=readline()
ans,cur=0,0
a,suma=-1,0
b,sumb=n,0
while True:
if a>=b: break
elif suma>sumb:
b-=1
sumb+=arr[b]
cur+=1
elif {{completion}}:
a+=1
suma+=arr[a]
cur+=1
else :
ans=cur
a+=1
b-=1
suma+=arr[a]
sumb+=arr[b]
cur+=2
print(ans)
if __name__ == "__main__":
T=read()
for i in range(T):
solve()
|
suma<sumb
|
[{"input": "4\n3\n10 20 10\n6\n2 1 4 2 4 1\n5\n1 2 4 8 16\n9\n7 3 20 5 15 1 11 8 10", "output": ["2\n6\n0\n7"]}]
|
control_completion_000795
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
Input Specification: The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ Β β the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ Β β the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
Code:
I=input
for _ in [0]*int(I()):
I();p,z,zero=0,1,0
for v in I().split():
p+=int(v)
if zero and p>0:z=0;break
if # TODO: Your code here:zero=True
if p<0:z=0;break
print(['NO','YES'][zero and z])
|
I=input
for _ in [0]*int(I()):
I();p,z,zero=0,1,0
for v in I().split():
p+=int(v)
if zero and p>0:z=0;break
if {{completion}}:zero=True
if p<0:z=0;break
print(['NO','YES'][zero and z])
|
p==0
|
[{"input": "7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0", "output": ["No\nYes\nNo\nNo\nYes\nYes\nYes"]}]
|
control_completion_000418
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: During their training for the ICPC competitions, team "Jee You See" stumbled upon a very basic counting problem. After many "Wrong answer" verdicts, they finally decided to give up and destroy turn-off the PC. Now they want your help in up-solving the problem.You are given 4 integers $$$n$$$, $$$l$$$, $$$r$$$, and $$$z$$$. Count the number of arrays $$$a$$$ of length $$$n$$$ containing non-negative integers such that: $$$l\le a_1+a_2+\ldots+a_n\le r$$$, and $$$a_1\oplus a_2 \oplus \ldots\oplus a_n=z$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Since the answer can be large, print it modulo $$$10^9+7$$$.
Input Specification: The only line contains four integers $$$n$$$, $$$l$$$, $$$r$$$, $$$z$$$ ($$$1 \le n \le 1000$$$, $$$1\le l\le r\le 10^{18}$$$, $$$1\le z\le 10^{18}$$$).
Output Specification: Print the number of arrays $$$a$$$ satisfying all requirements modulo $$$10^9+7$$$.
Notes: NoteThe following arrays satisfy the conditions for the first sample: $$$[1, 0, 0]$$$; $$$[0, 1, 0]$$$; $$$[3, 2, 0]$$$; $$$[2, 3, 0]$$$; $$$[0, 0, 1]$$$; $$$[1, 1, 1]$$$; $$$[2, 2, 1]$$$; $$$[3, 0, 2]$$$; $$$[2, 1, 2]$$$; $$$[1, 2, 2]$$$; $$$[0, 3, 2]$$$; $$$[2, 0, 3]$$$; $$$[0, 2, 3]$$$. The following arrays satisfy the conditions for the second sample: $$$[2, 0, 0, 0]$$$; $$$[0, 2, 0, 0]$$$; $$$[0, 0, 2, 0]$$$; $$$[0, 0, 0, 2]$$$.
Code:
import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
N = 10000
fact = [0 for _ in range(N)]
invfact = [0 for _ in range(N)]
fact[0] = 1
for i in range(1, N):
fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):
invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):
if k < 0 or n < k:
return 0
else:
return (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD
def nHk(n, k):
return nCk(n + k - 1, k)
def main():
n, l, r, z = map(int, input().split())
bit = [0] * 60
for i in range(60):
if z >> i & 1:
bit[i] = 1
r -= 1 << i
l -= 1 << i
if r < 0:
print(0)
return
ma = [0] * 60
for i in range(60):
if n % 2 == bit[i]:
nn = n
else:
nn = n - 1
ma[i] = (1 << (i + 1)) * nn
if i != 0:
ma[i] += ma[i - 1]
tot = [0] * 60
for i in range(60):
for j in range(bit[i], n + 1, 2):
tot[i] += nCk(n, j)
tot[i] %= MOD
if i != 0:
tot[i] *= tot[i - 1]
tot[i] %= MOD
memo = {}
d = r - l
bi = [1 << i for i in range(61)]
def solve(i, l):
r = l + d
if l <= 0 and ma[i] <= r:
return tot[i]
elif ma[i] < l:
return 0
elif i == -1:
return l <= 0
elif i + 60 * l in memo:
return memo[i + 60 * l]
ret = 0
mi = bi[i + 1]
ll = l
rr = r
for j in range(bit[i], n + 1, 2):
ret += solve(i - 1, ll) * nCk(n, j) % MOD
if ret >= MOD: ret -= MOD
ll -= mi
rr -= mi
if rr < 0:
# TODO: Your code here
memo[i + 60 * l] = ret
return ret
ans = solve(59, l)
print(ans)
for _ in range(1):
main()
|
import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
N = 10000
fact = [0 for _ in range(N)]
invfact = [0 for _ in range(N)]
fact[0] = 1
for i in range(1, N):
fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):
invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):
if k < 0 or n < k:
return 0
else:
return (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD
def nHk(n, k):
return nCk(n + k - 1, k)
def main():
n, l, r, z = map(int, input().split())
bit = [0] * 60
for i in range(60):
if z >> i & 1:
bit[i] = 1
r -= 1 << i
l -= 1 << i
if r < 0:
print(0)
return
ma = [0] * 60
for i in range(60):
if n % 2 == bit[i]:
nn = n
else:
nn = n - 1
ma[i] = (1 << (i + 1)) * nn
if i != 0:
ma[i] += ma[i - 1]
tot = [0] * 60
for i in range(60):
for j in range(bit[i], n + 1, 2):
tot[i] += nCk(n, j)
tot[i] %= MOD
if i != 0:
tot[i] *= tot[i - 1]
tot[i] %= MOD
memo = {}
d = r - l
bi = [1 << i for i in range(61)]
def solve(i, l):
r = l + d
if l <= 0 and ma[i] <= r:
return tot[i]
elif ma[i] < l:
return 0
elif i == -1:
return l <= 0
elif i + 60 * l in memo:
return memo[i + 60 * l]
ret = 0
mi = bi[i + 1]
ll = l
rr = r
for j in range(bit[i], n + 1, 2):
ret += solve(i - 1, ll) * nCk(n, j) % MOD
if ret >= MOD: ret -= MOD
ll -= mi
rr -= mi
if rr < 0:
{{completion}}
memo[i + 60 * l] = ret
return ret
ans = solve(59, l)
print(ans)
for _ in range(1):
main()
|
break
|
[{"input": "3 1 5 1", "output": ["13"]}, {"input": "4 1 3 2", "output": ["4"]}, {"input": "2 1 100000 15629", "output": ["49152"]}, {"input": "100 56 89 66", "output": ["981727503"]}]
|
block_completion_006066
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \leq i \leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \leq i \leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)?
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) β the elements of the array $$$a$$$.
Output Specification: Print a single integer, the minimum number of moves to make $$$b$$$ increasing.
Notes: NoteExample $$$1$$$: you can subtract $$$a_1$$$ from $$$b_1$$$, and add $$$a_3$$$, $$$a_4$$$, and $$$a_5$$$ to $$$b_3$$$, $$$b_4$$$, and $$$b_5$$$ respectively. The final array will be [$$$-1$$$, $$$0$$$, $$$3$$$, $$$4$$$, $$$5$$$] after $$$4$$$ moves.Example $$$2$$$: you can reach [$$$-3$$$, $$$-2$$$, $$$-1$$$, $$$0$$$, $$$1$$$, $$$2$$$, $$$3$$$] in $$$10$$$ moves.
Code:
from math import ceil
n=int(input())
a=list(map(int,input().split()))
ans=float("inf")
for i in range(len(a)):
t=[0]*n
temp=0
j=i-1
prev =0
while # TODO: Your code here:
x=(ceil((prev+1)/a[j]))
temp+=x
prev=(a[j]*x)
j-=1
k=i+1
prev=0
while k<len(a):
x=(ceil((prev+1)/a[k]))
temp+=x
prev=(a[k]*x)
k+=1
ans=min(ans,temp)
print(int(ans))
|
from math import ceil
n=int(input())
a=list(map(int,input().split()))
ans=float("inf")
for i in range(len(a)):
t=[0]*n
temp=0
j=i-1
prev =0
while {{completion}}:
x=(ceil((prev+1)/a[j]))
temp+=x
prev=(a[j]*x)
j-=1
k=i+1
prev=0
while k<len(a):
x=(ceil((prev+1)/a[k]))
temp+=x
prev=(a[k]*x)
k+=1
ans=min(ans,temp)
print(int(ans))
|
j>=0
|
[{"input": "5\n1 2 3 4 5", "output": ["4"]}, {"input": "7\n1 2 1 2 1 2 1", "output": ["10"]}, {"input": "8\n1 8 2 7 3 6 4 5", "output": ["16"]}]
|
control_completion_000962
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order: the root has index $$$1$$$; if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way: if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$; otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree: choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.
Output Specification: Print one integer β the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.
Code:
mod=998244353
cnt=0
n=int(input())
s=input()
import random
q=random.randint(10**9,2*10**9)
p=random.randint(10**9,2*10**9)
r=10**9+7
a=[-1]
for i in s:
if i=='A':
a.append(p)
else:
# TODO: Your code here
for i in range(2**(n-1)-1,0,-1):
if a[2*i]!=a[2*i+1]:
cnt+=1
a[i]=a[i]^(2*a[2*i]+2*a[2*i+1])
a[i]%=r
print(pow(2,cnt,mod))
|
mod=998244353
cnt=0
n=int(input())
s=input()
import random
q=random.randint(10**9,2*10**9)
p=random.randint(10**9,2*10**9)
r=10**9+7
a=[-1]
for i in s:
if i=='A':
a.append(p)
else:
{{completion}}
for i in range(2**(n-1)-1,0,-1):
if a[2*i]!=a[2*i+1]:
cnt+=1
a[i]=a[i]^(2*a[2*i]+2*a[2*i+1])
a[i]%=r
print(pow(2,cnt,mod))
|
a.append(q)
|
[{"input": "4\nBAAAAAAAABBABAB", "output": ["16"]}, {"input": "2\nBAA", "output": ["1"]}, {"input": "2\nABA", "output": ["2"]}, {"input": "2\nAAB", "output": ["2"]}, {"input": "2\nAAA", "output": ["1"]}]
|
block_completion_001704
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
Input Specification: The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) β the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' β the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) β the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
Output Specification: Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
Code:
n,m,q=map(int,input().split())
z=[] # 2d
a=[] # 1d
c=0 # count icons
ans=0
for i in range(n):
z.append(list(input()))
for i in range(m):
for j in range(n):
if z[j][i]=="*":
a.append(1)
c+=1
else:
a.append(0)
ans=c
for i in range(c):
if a[i]==1:
ans-=1
for i in range(q):
x,y=map(int,input().split())
if a[n*(y-1)+x-1]==1:
a[n*(y-1)+x-1]=0
c-=1
if n*(y-1)+x-1 > c:
ans-=1
if a[c]==1:
ans+=1
elif a[n*(y-1)+x-1]==0: # xor
a[n*(y-1)+x-1]=1
c+=1
if n*(y-1)+x-1 >= c-1: # c or c-1?
ans+=1
if c: # if c>0
if a[c-1]==1:
# TODO: Your code here
print(ans)
|
n,m,q=map(int,input().split())
z=[] # 2d
a=[] # 1d
c=0 # count icons
ans=0
for i in range(n):
z.append(list(input()))
for i in range(m):
for j in range(n):
if z[j][i]=="*":
a.append(1)
c+=1
else:
a.append(0)
ans=c
for i in range(c):
if a[i]==1:
ans-=1
for i in range(q):
x,y=map(int,input().split())
if a[n*(y-1)+x-1]==1:
a[n*(y-1)+x-1]=0
c-=1
if n*(y-1)+x-1 > c:
ans-=1
if a[c]==1:
ans+=1
elif a[n*(y-1)+x-1]==0: # xor
a[n*(y-1)+x-1]=1
c+=1
if n*(y-1)+x-1 >= c-1: # c or c-1?
ans+=1
if c: # if c>0
if a[c-1]==1:
{{completion}}
print(ans)
|
ans-=1
|
[{"input": "4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "output": ["3\n4\n4\n3\n4\n5\n5\n5"]}, {"input": "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3", "output": ["2\n3\n3\n3\n2"]}]
|
block_completion_007869
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. The $$$i$$$-th column has the bottom $$$a_i$$$ cells blocked (the cells in rows $$$1, 2, \dots, a_i$$$), the remaining $$$n - a_i$$$ cells are unblocked.A robot is travelling across this grid. You can send it commandsΒ β move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.However, the robot is brokenΒ β it executes each received command $$$k$$$ times. So if you tell it to move up, for example, it will move up $$$k$$$ times ($$$k$$$ cells). You can't send it commands while the robot executes the current one.You are asked $$$q$$$ queries about the robot. Each query has a start cell, a finish cell and a value $$$k$$$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times?The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 2 \cdot 10^5$$$)Β β the number of rows and columns of the grid. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$0 \le a_i \le n$$$)Β β the number of blocked cells on the bottom of the $$$i$$$-th column. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$)Β β the number of queries. Each of the next $$$q$$$ lines contain five integers $$$x_s, y_s, x_f, y_f$$$ and $$$k$$$ ($$$a[y_s] < x_s \le n$$$; $$$1 \le y_s \le m$$$; $$$a[y_f] < x_f \le n$$$; $$$1 \le y_f \le m$$$; $$$1 \le k \le 10^9$$$)Β β the row and the column of the start cell, the row and the column of the finish cell and the number of times each your command is executed. The start and the finish cell of each query are unblocked.
Output Specification: For each query, print "YES" if you can send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times. Otherwise, print "NO".
Code:
import sys
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
debug = lambda *x: print(*x, file=sys.stderr)
out = []
class sparse_table:
def __init__(self, n, a, default=0, func=max):
self.n, self.lg = n, 20
self.func = func
self.table = [array('i', [default] * n) for _ in range(self.lg)]
self.table[0] = a
self.preprocess()
def preprocess(self):
for j in range(1, self.lg):
i = 0
while # TODO: Your code here:
ix = i + (1 << (j - 1))
self.table[j][i] = self.func(self.table[j - 1][i], self.table[j - 1][ix])
i += 1
def quary(self, l, r):
'''[l,r]'''
l1 = (r - l + 1).bit_length() - 1
r1 = r - (1 << l1) + 1
return self.func(self.table[l1][l], self.table[l1][r1])
n, m = inp(int)
a = array('i', inp(int))
mem = sparse_table(m, a)
for _ in range(int(input())):
xs, ys, xf, yf, k = inp(int)
div, mod = divmod(n - xs, k)
xma = n - mod
qur = mem.quary(min(ys, yf) - 1, max(ys, yf) - 1)
if qur >= xma or abs(xma - xf) % k or abs(ys - yf) % k:
out.append('no')
else:
out.append('yes')
print('\n'.join(out))
|
import sys
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
debug = lambda *x: print(*x, file=sys.stderr)
out = []
class sparse_table:
def __init__(self, n, a, default=0, func=max):
self.n, self.lg = n, 20
self.func = func
self.table = [array('i', [default] * n) for _ in range(self.lg)]
self.table[0] = a
self.preprocess()
def preprocess(self):
for j in range(1, self.lg):
i = 0
while {{completion}}:
ix = i + (1 << (j - 1))
self.table[j][i] = self.func(self.table[j - 1][i], self.table[j - 1][ix])
i += 1
def quary(self, l, r):
'''[l,r]'''
l1 = (r - l + 1).bit_length() - 1
r1 = r - (1 << l1) + 1
return self.func(self.table[l1][l], self.table[l1][r1])
n, m = inp(int)
a = array('i', inp(int))
mem = sparse_table(m, a)
for _ in range(int(input())):
xs, ys, xf, yf, k = inp(int)
div, mod = divmod(n - xs, k)
xma = n - mod
qur = mem.quary(min(ys, yf) - 1, max(ys, yf) - 1)
if qur >= xma or abs(xma - xf) % k or abs(ys - yf) % k:
out.append('no')
else:
out.append('yes')
print('\n'.join(out))
|
i + (1 << j) - 1 < self.n
|
[{"input": "11 10\n9 0 0 10 3 4 8 11 10 8\n6\n1 2 1 3 1\n1 2 1 3 2\n4 3 4 5 2\n5 3 11 5 3\n5 3 11 5 2\n11 9 9 10 1", "output": ["YES\nNO\nNO\nNO\nYES\nYES"]}]
|
control_completion_002944
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns with each cell having a non-negative integer written on it. Timur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is maximal. The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. Help him find the maximal sum he can get.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 200$$$, $$$1 \leq m \leq 200$$$). The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element of the $$$i$$$-th line $$$a_{ij}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row $$$(0\leq a_{ij} \leq 10^6)$$$ It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$4\cdot10^4$$$.
Output Specification: For each test case output a single integer, the maximum sum over all possible placements of the bishop.
Notes: NoteFor the first test case here the best sum is achieved by the bishop being in this position:
Code:
# auther: codeCell
for _ in range(int(input())):
n,m=map(int,input().split())
a = [ [*map(int, input().split())] for _ in range(n)]
u = [0]*(n+m-1)
v = [0]*(n+m-1)
for i in range(n):
for j in range(m):
# TODO: Your code here
for i in range(n):
for j in range(m):
a[i][j] = u[i+j] + v[i-j] - a[i][j]
print(max(map(max,a)))
|
# auther: codeCell
for _ in range(int(input())):
n,m=map(int,input().split())
a = [ [*map(int, input().split())] for _ in range(n)]
u = [0]*(n+m-1)
v = [0]*(n+m-1)
for i in range(n):
for j in range(m):
{{completion}}
for i in range(n):
for j in range(m):
a[i][j] = u[i+j] + v[i-j] - a[i][j]
print(max(map(max,a)))
|
u[i+j] += a[i][j]
v[i-j] += a[i][j]
|
[{"input": "4\n4 4\n1 2 2 1\n2 4 2 4\n2 2 3 1\n2 4 2 4\n2 1\n1\n0\n3 3\n1 1 1\n1 1 1\n1 1 1\n3 3\n0 1 1\n1 0 1\n1 1 0", "output": ["20\n1\n5\n3"]}]
|
block_completion_007693
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is the hard version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1' ($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good? Meanwhile, she also wants to know the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.
Input Specification: The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$)Β β the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$)Β β the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print a single line with two integersΒ β the minimum number of operations to make $$$s$$$ good, and the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.
Notes: NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively, the number of subsegments of it is $$$2$$$. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100", the number of subsegments of them are $$$2$$$, $$$4$$$, $$$4$$$ respectively. It's easy to find that the minimum number of subsegments among all solutions with the minimum number of operations is $$$2$$$.In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.
Code:
for _ in range(int(input().strip())):
n = int(input().strip())
arr = input()
ans = 0
t = []
for i in range(0, len(arr), 2):
if # TODO: Your code here:
ans += 1
else:
t.append(arr[i])
seg = 1
for i in range(0, len(t) - 1):
if t[i] != t[i + 1]:
seg += 1
print(ans, seg)
|
for _ in range(int(input().strip())):
n = int(input().strip())
arr = input()
ans = 0
t = []
for i in range(0, len(arr), 2):
if {{completion}}:
ans += 1
else:
t.append(arr[i])
seg = 1
for i in range(0, len(t) - 1):
if t[i] != t[i + 1]:
seg += 1
print(ans, seg)
|
arr[i] != arr[i + 1]
|
[{"input": "5\n10\n1110011000\n8\n11001111\n2\n00\n2\n11\n6\n100110", "output": ["3 2\n0 3\n0 1\n0 1\n3 1"]}]
|
control_completion_007950
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i.βe. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array.
Input Specification: The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query.
Output Specification: For each query, print one integerΒ β the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query.
Notes: NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$.
Code:
import sys; input = sys.stdin.readline
def seg(start, end):
if start == end:
# TODO: Your code here
mid = (start + end) // 2
l = seg(start, mid)
r = seg(mid + 1, end)
result = []
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
l, r = r, l
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
return result
n = int(input())
l = 1 << n
arr = list(map(int, input().split()))
tree = seg(0, l - 1)
i = 0
for _ in range(int(input())):
i ^= (1 << int(input()))
print(tree[i][0])
|
import sys; input = sys.stdin.readline
def seg(start, end):
if start == end:
{{completion}}
mid = (start + end) // 2
l = seg(start, mid)
r = seg(mid + 1, end)
result = []
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
l, r = r, l
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
return result
n = int(input())
l = 1 << n
arr = list(map(int, input().split()))
tree = seg(0, l - 1)
i = 0
for _ in range(int(input())):
i ^= (1 << int(input()))
print(tree[i][0])
|
val = max(arr[start], 0)
return [(val, val, val, arr[start])]
|
[{"input": "3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1", "output": ["18\n8\n13"]}]
|
block_completion_008315
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n+1$$$ teleporters on a straight line, located in points $$$0$$$, $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$. It's possible to teleport from point $$$x$$$ to point $$$y$$$ if there are teleporters in both of those points, and it costs $$$(x-y)^2$$$ energy.You want to install some additional teleporters so that it is possible to get from the point $$$0$$$ to the point $$$a_n$$$ (possibly through some other teleporters) spending no more than $$$m$$$ energy in total. Each teleporter you install must be located in an integer point.What is the minimum number of teleporters you have to install?
Input Specification: The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 < a_2 < a_3 < \dots < a_n \le 10^9$$$). The third line contains one integer $$$m$$$ ($$$a_n \le m \le 10^{18}$$$).
Output Specification: Print one integer β the minimum number of teleporters you have to install so that it is possible to get from $$$0$$$ to $$$a_n$$$ spending at most $$$m$$$ energy. It can be shown that it's always possible under the constraints from the input format.
Code:
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
def ff(gap, ints):
sml = gap // ints
bigcount = gap % ints
return bigcount * (sml + 1) ** 2 + (ints - bigcount) * sml ** 2
def f(gap, c):
if c > gap ** 2 // 2:
return 0, gap ** 2
sml = 0
big = gap
while big - sml > 1:
mid = (big + sml) // 2
a = ff(gap, mid)
b = ff(gap, mid + 1)
if a - b >= c:
sml = mid
else:
# TODO: Your code here
return sml, ff(gap, big)
n, = I()
a = I()
m, = I()
gaps = [a[0]]
for i in range(n - 1):
gaps.append(a[i + 1] - a[i])
sml = 2
big = 1 << 59 + 2
while big - sml > 1:
cost = 0
mid = (big + sml) // 2
for g in gaps:
a, c = f(g, mid)
cost += c
if cost > m:
big = mid
else:
sml = mid
abig = 0
cbig = 0
for g in gaps:
a, c = f(g, big)
abig += a
cbig += c
print(abig + max(0, (cbig - m - 1) // sml + 1))
|
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
def ff(gap, ints):
sml = gap // ints
bigcount = gap % ints
return bigcount * (sml + 1) ** 2 + (ints - bigcount) * sml ** 2
def f(gap, c):
if c > gap ** 2 // 2:
return 0, gap ** 2
sml = 0
big = gap
while big - sml > 1:
mid = (big + sml) // 2
a = ff(gap, mid)
b = ff(gap, mid + 1)
if a - b >= c:
sml = mid
else:
{{completion}}
return sml, ff(gap, big)
n, = I()
a = I()
m, = I()
gaps = [a[0]]
for i in range(n - 1):
gaps.append(a[i + 1] - a[i])
sml = 2
big = 1 << 59 + 2
while big - sml > 1:
cost = 0
mid = (big + sml) // 2
for g in gaps:
a, c = f(g, mid)
cost += c
if cost > m:
big = mid
else:
sml = mid
abig = 0
cbig = 0
for g in gaps:
a, c = f(g, big)
abig += a
cbig += c
print(abig + max(0, (cbig - m - 1) // sml + 1))
|
big = mid
|
[{"input": "2\n1 5\n7", "output": ["2"]}, {"input": "2\n1 5\n6", "output": ["3"]}, {"input": "1\n5\n5", "output": ["4"]}, {"input": "1\n1000000000\n1000000043", "output": ["999999978"]}]
|
block_completion_003463
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: The robot is placed in the top left corner of a grid, consisting of $$$n$$$ rows and $$$m$$$ columns, in a cell $$$(1, 1)$$$.In one step, it can move into a cell, adjacent by a side to the current one: $$$(x, y) \rightarrow (x, y + 1)$$$; $$$(x, y) \rightarrow (x + 1, y)$$$; $$$(x, y) \rightarrow (x, y - 1)$$$; $$$(x, y) \rightarrow (x - 1, y)$$$. The robot can't move outside the grid.The cell $$$(s_x, s_y)$$$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $$$d$$$ to the laser, it gets evaporated. The distance between two cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.Print the smallest number of steps that the robot can take to reach the cell $$$(n, m)$$$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $$$(n, m)$$$, print -1.The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $$$d$$$ to the laser.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of testcases. The only line of each testcase contains five integers $$$n, m, s_x, s_y, d$$$ ($$$2 \le n, m \le 1000$$$; $$$1 \le s_x \le n$$$; $$$1 \le s_y \le m$$$; $$$0 \le d \le n + m$$$)Β β the size of the grid, the cell that contains the laser and the evaporating distance of the laser. The laser is neither in the starting cell, nor in the ending cell ($$$(s_x, s_y) \neq (1, 1)$$$ and $$$(s_x, s_y) \neq (n, m)$$$). The starting cell $$$(1, 1)$$$ always has distance greater than $$$d$$$ to the laser ($$$|s_x - 1| + |s_y - 1| > d$$$).
Output Specification: For each testcase, print a single integer. If it's possible to reach the cell $$$(n, m)$$$ from $$$(1, 1)$$$ without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1.
Code:
import sys
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
# TODO: Your code here
for l in ls:
sys.stderr.write(l + ('\n'))
sys.stderr.write("-- output --\n")
def ins(u, mn, mx):
return u[0] >= mn[0] and u[1] >= mn[1] and u[0] <= mx[0] and u[1] <= mx[1]
def clmp(x, n):
if x < 0: return 0
if x >= n: return n-1
return x
def clp(u, n, m):
return (clmp(u[0], n), clmp(u[1], m))
def d(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def solve(n, m, sx, sy, d):
if d ==0: return n+m-2
smin = clp((sx-d, sy-d), n, m)
smax = clp((sx+d, sy+d), n, m)
if abs(smax[0]-smin[0]) >= n-1 or abs(smax[1]-smin[1]) >= m-1: return -1
if ins((0, 0), smin, smax) or ins((n-1, m-1), smin, smax) : return -1
return n+m-2
for l in ls[1:]:
n, m, sx, sy, d = [int(x) for x in l.split(' ')]
print(solve(n, m, sx-1, sy-1, d))
|
import sys
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
{{completion}}
for l in ls:
sys.stderr.write(l + ('\n'))
sys.stderr.write("-- output --\n")
def ins(u, mn, mx):
return u[0] >= mn[0] and u[1] >= mn[1] and u[0] <= mx[0] and u[1] <= mx[1]
def clmp(x, n):
if x < 0: return 0
if x >= n: return n-1
return x
def clp(u, n, m):
return (clmp(u[0], n), clmp(u[1], m))
def d(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def solve(n, m, sx, sy, d):
if d ==0: return n+m-2
smin = clp((sx-d, sy-d), n, m)
smax = clp((sx+d, sy+d), n, m)
if abs(smax[0]-smin[0]) >= n-1 or abs(smax[1]-smin[1]) >= m-1: return -1
if ins((0, 0), smin, smax) or ins((n-1, m-1), smin, smax) : return -1
return n+m-2
for l in ls[1:]:
n, m, sx, sy, d = [int(x) for x in l.split(' ')]
print(solve(n, m, sx-1, sy-1, d))
|
ls.append(lst)
|
[{"input": "3\n\n2 3 1 3 0\n\n2 3 1 3 1\n\n5 5 3 4 1", "output": ["3\n-1\n8"]}]
|
block_completion_002786
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
from collections import *
from itertools import *
from functools import *
import math,sys
input = sys.stdin.buffer.readline
n = int(input())
AB = [tuple(map(int,input().split())) for _ in range(n)]
M = int(input())
XY = [tuple(map(int,input().split())) for _ in range(M)]
ans = []
from math import gcd
def modinv(a, b):
p = b
x, y, u, v = 1, 0, 0, 1
while b:
k = a // b
x -= k * u
y -= k * v
x, u = u, x
y, v = v, y
a, b = b, a % b
x %= p
if x < 0:
x += p
return x
def slc(A, B, mod):
#solve Ax=B mod
a = A
b = B
m = mod
d = gcd(a,gcd(b,m))
while d>1:
a //= d
b //= d
m //= d
d = gcd(a,gcd(b,m))
if gcd(a,m) != 1:
return -1
return (modinv(a,m)*b)%m
D = [a-b for a,b in AB]
S = sum(b for a,b in AB)
D.sort(reverse=True)
SD = list(accumulate([0]+D))
L = 0
for i in range(n-1,-1,-1):
if D[i]>0:
L = i+1
break
for x,y in XY:
d = gcd(x,y)
if n%d != 0:
print(-1)
continue
x0 = slc(x,n,y)
tb = y//d
ok = 0
ng = -10**10
while ok-ng>1:
mid = (ok+ng)//2
if x0+mid*tb >=0:
ok = mid
else:
# TODO: Your code here
x0 += tb*ok
if x0*x>n:
print(-1)
continue
def is_ok(k):
return ((n-x*(x0 + k*tb)) >= 0)&(x0 + k*tb >= 0)
k0 = (L-x*x0)//(tb*x)
ans = -1
flg = False
if is_ok(k0):
tmp = S + SD[x*(x0 + k0*tb)]
ans = max(ans,tmp)
if is_ok(k0+1):
tmp = S + SD[x*(x0 + (k0+1)*tb)]
ans = max(ans,tmp)
flg = True
if flg:
print(ans)
continue
ok = 0
ng = k0 + 1
while ng-ok>1:
mid = (ok+ng)//2
if is_ok(mid):
ok = mid
else:
ng = mid
ans = max(ans,S + SD[x*(x0 + ok*tb)])
print(ans)
|
from collections import *
from itertools import *
from functools import *
import math,sys
input = sys.stdin.buffer.readline
n = int(input())
AB = [tuple(map(int,input().split())) for _ in range(n)]
M = int(input())
XY = [tuple(map(int,input().split())) for _ in range(M)]
ans = []
from math import gcd
def modinv(a, b):
p = b
x, y, u, v = 1, 0, 0, 1
while b:
k = a // b
x -= k * u
y -= k * v
x, u = u, x
y, v = v, y
a, b = b, a % b
x %= p
if x < 0:
x += p
return x
def slc(A, B, mod):
#solve Ax=B mod
a = A
b = B
m = mod
d = gcd(a,gcd(b,m))
while d>1:
a //= d
b //= d
m //= d
d = gcd(a,gcd(b,m))
if gcd(a,m) != 1:
return -1
return (modinv(a,m)*b)%m
D = [a-b for a,b in AB]
S = sum(b for a,b in AB)
D.sort(reverse=True)
SD = list(accumulate([0]+D))
L = 0
for i in range(n-1,-1,-1):
if D[i]>0:
L = i+1
break
for x,y in XY:
d = gcd(x,y)
if n%d != 0:
print(-1)
continue
x0 = slc(x,n,y)
tb = y//d
ok = 0
ng = -10**10
while ok-ng>1:
mid = (ok+ng)//2
if x0+mid*tb >=0:
ok = mid
else:
{{completion}}
x0 += tb*ok
if x0*x>n:
print(-1)
continue
def is_ok(k):
return ((n-x*(x0 + k*tb)) >= 0)&(x0 + k*tb >= 0)
k0 = (L-x*x0)//(tb*x)
ans = -1
flg = False
if is_ok(k0):
tmp = S + SD[x*(x0 + k0*tb)]
ans = max(ans,tmp)
if is_ok(k0+1):
tmp = S + SD[x*(x0 + (k0+1)*tb)]
ans = max(ans,tmp)
flg = True
if flg:
print(ans)
continue
ok = 0
ng = k0 + 1
while ng-ok>1:
mid = (ok+ng)//2
if is_ok(mid):
ok = mid
else:
ng = mid
ans = max(ans,S + SD[x*(x0 + ok*tb)])
print(ans)
|
ng = mid
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005535
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek is participating in a lemper cooking competition. In the competition, Pak Chanek has to cook lempers with $$$N$$$ stoves that are arranged sequentially from stove $$$1$$$ to stove $$$N$$$. Initially, stove $$$i$$$ has a temperature of $$$A_i$$$ degrees. A stove can have a negative temperature.Pak Chanek realises that, in order for his lempers to be cooked, he needs to keep the temperature of each stove at a non-negative value. To make it happen, Pak Chanek can do zero or more operations. In one operation, Pak Chanek chooses one stove $$$i$$$ with $$$2 \leq i \leq N-1$$$, then: changes the temperature of stove $$$i-1$$$ into $$$A_{i-1} := A_{i-1} + A_{i}$$$, changes the temperature of stove $$$i+1$$$ into $$$A_{i+1} := A_{i+1} + A_{i}$$$, and changes the temperature of stove $$$i$$$ into $$$A_i := -A_i$$$. Pak Chanek wants to know the minimum number of operations he needs to do such that the temperatures of all stoves are at non-negative values. Help Pak Chanek by telling him the minimum number of operations needed or by reporting if it is not possible to do.
Input Specification: The first line contains a single integer $$$N$$$ ($$$1 \le N \le 10^5$$$) β the number of stoves. The second line contains $$$N$$$ integers $$$A_1, A_2, \ldots, A_N$$$ ($$$-10^9 \leq A_i \leq 10^9$$$) β the initial temperatures of the stoves.
Output Specification: Output an integer representing the minimum number of operations needed to make the temperatures of all stoves at non-negative values or output $$$-1$$$ if it is not possible.
Notes: NoteFor the first example, a sequence of operations that can be done is as follows: Pak Chanek does an operation to stove $$$3$$$, $$$A = [2, -2, 1, 4, 2, -2, 9]$$$. Pak Chanek does an operation to stove $$$2$$$, $$$A = [0, 2, -1, 4, 2, -2, 9]$$$. Pak Chanek does an operation to stove $$$3$$$, $$$A = [0, 1, 1, 3, 2, -2, 9]$$$. Pak Chanek does an operation to stove $$$6$$$, $$$A = [0, 1, 1, 3, 0, 2, 7]$$$. There is no other sequence of operations such that the number of operations needed is fewer than $$$4$$$.
Code:
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, data, default=0, func=lambda x, y: x+y):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
# TODO: Your code here
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def process(A):
n = len(A)
A1 = []
curr = 0
for i in range(n):
curr+=A[i]
A1.append([curr, i])
if min(A1)[0] < 0 or max(A1)[0] != A1[-1][0]:
print("-1")
return
A1.sort()
A1 = [[i, A1[i][1]] for i in range(n)]
A1.sort(key=lambda a:a[1])
S = SegmentTree(data=[0 for i in range(n)])
answer = 0
for x, i in A1:
answer+=S.query(x+1, n)
S[x] = 1
print(answer)
n = int(input())
A = [int(x) for x in input().split()]
process(A)
|
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, data, default=0, func=lambda x, y: x+y):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
{{completion}}
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def process(A):
n = len(A)
A1 = []
curr = 0
for i in range(n):
curr+=A[i]
A1.append([curr, i])
if min(A1)[0] < 0 or max(A1)[0] != A1[-1][0]:
print("-1")
return
A1.sort()
A1 = [[i, A1[i][1]] for i in range(n)]
A1.sort(key=lambda a:a[1])
S = SegmentTree(data=[0 for i in range(n)])
answer = 0
for x, i in A1:
answer+=S.query(x+1, n)
S[x] = 1
print(answer)
n = int(input())
A = [int(x) for x in input().split()]
process(A)
|
res_left = self._func(res_left, self.data[start])
start += 1
|
[{"input": "7\n2 -1 -1 5 2 -2 9", "output": ["4"]}, {"input": "5\n-1 -2 -3 -4 -5", "output": ["-1"]}]
|
block_completion_003791
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for _ in range(int(input())):
# TODO: Your code here
|
for _ in range(int(input())):
{{completion}}
|
input()
a, b, *_, c, d = sorted(map(int, input().split()))
print(c+d-a-b)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005388
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if # TODO: Your code here:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
res += [1] * (j-i)
st = j
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if {{completion}}:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
res += [1] * (j-i)
st = j
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
word != 0
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
control_completion_005832
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Recently in Divanovo, a huge river locks system was built. There are now $$$n$$$ locks, the $$$i$$$-th of them has the volume of $$$v_i$$$ liters, so that it can contain any amount of water between $$$0$$$ and $$$v_i$$$ liters. Each lock has a pipe attached to it. When the pipe is open, $$$1$$$ liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $$$i$$$ to the lock $$$i + 1$$$. If the lock $$$i + 1$$$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $$$5$$$ locks with two open pipes at locks $$$1$$$ and $$$3$$$. Because locks $$$1$$$, $$$3$$$, and $$$4$$$ are already filled, effectively the water goes to locks $$$2$$$ and $$$5$$$. Note that the volume of the $$$i$$$-th lock may be greater than the volume of the $$$i + 1$$$-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $$$q$$$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $$$j$$$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $$$t_j$$$ seconds.Please help the mayor to solve this tricky problem and answer his queries.
Input Specification: The first lines contains one integer $$$n$$$ ($$$1 \le n \le 200\,000$$$)Β β the number of locks. The second lines contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$1 \le v_i \le 10^9$$$))Β β volumes of the locks. The third line contains one integer $$$q$$$ ($$$1 \le q \le 200\,000$$$)Β β the number of queries. Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \le t_j \le 10^9$$$)Β β the number of seconds you have to fill all the locks in the query $$$j$$$.
Output Specification: Print $$$q$$$ integers. The $$$j$$$-th of them should be equal to the minimum number of pipes to turn on so that after $$$t_j$$$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $$$-1$$$.
Notes: NoteThere are $$$6$$$ queries in the first example test. In the queries $$$1, 3, 4$$$ the answer is $$$-1$$$. We need to wait $$$4$$$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$. After $$$4$$$ seconds the locks $$$1$$$ and $$$4$$$ are full. In the following $$$1$$$ second $$$1$$$ liter of water is transferred to the locks $$$2$$$ and $$$5$$$. The lock $$$3$$$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$.In the fifth query one can open pipes $$$1, 2, 3, 4$$$.
Code:
from sys import stdin, stderr
def debug(*args, **kwargs):
print(*args, file=stderr, **kwargs)
_, volumes, _, *queries = stdin.readlines()
volumes = map(int, volumes.split())
queries = map(int, queries)
s = t_min = 0
for i, v in enumerate(volumes, 1):
s += v
div, mod = divmod(s, i)
t_min = max(t_min, div + (mod != 0))
res = []
for q in map(int, queries):
if q < t_min:
ans = -1
else:
# TODO: Your code here
res.append(ans)
print('\n'.join(str(x) for x in res))
|
from sys import stdin, stderr
def debug(*args, **kwargs):
print(*args, file=stderr, **kwargs)
_, volumes, _, *queries = stdin.readlines()
volumes = map(int, volumes.split())
queries = map(int, queries)
s = t_min = 0
for i, v in enumerate(volumes, 1):
s += v
div, mod = divmod(s, i)
t_min = max(t_min, div + (mod != 0))
res = []
for q in map(int, queries):
if q < t_min:
ans = -1
else:
{{completion}}
res.append(ans)
print('\n'.join(str(x) for x in res))
|
div, mod = divmod(s, q)
ans = div + (mod != 0)
|
[{"input": "5\n4 1 5 4 1\n6\n1\n6\n2\n3\n4\n5", "output": ["-1\n3\n-1\n-1\n4\n3"]}, {"input": "5\n4 4 4 4 4\n6\n1\n3\n6\n5\n2\n4", "output": ["-1\n-1\n4\n4\n-1\n5"]}]
|
block_completion_004268
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
n,k=map(int,input().split())
a=[]
d={}
for i in range(n):
a+=[''.join(input().split())]
d[a[-1]]=0
def cal(s,t):
res=""
for # TODO: Your code here:
res+=str((9-int(s[i])-int(t[i]))%3)
return res
for i in range(n):
for j in range(i):
try:
d[cal(a[i],a[j])]+=1
except:
pass
ans=0
for y in d.values():
ans+=(y*(y-1))//2
print(ans)
|
n,k=map(int,input().split())
a=[]
d={}
for i in range(n):
a+=[''.join(input().split())]
d[a[-1]]=0
def cal(s,t):
res=""
for {{completion}}:
res+=str((9-int(s[i])-int(t[i]))%3)
return res
for i in range(n):
for j in range(i):
try:
d[cal(a[i],a[j])]+=1
except:
pass
ans=0
for y in d.values():
ans+=(y*(y-1))//2
print(ans)
|
i in range(k)
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
control_completion_005228
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) Β β the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) Β β elements of the permutation.
Output Specification: Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
Notes: NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
Code:
input = __import__('sys').stdin.readline
n = int(input())
a = list(map(int, input().split())) + [n+1]
cache = {}
def check(i, u, d):
keys = []
j = i
while j+1 <= n:
key = (j, u, d)
v = cache.get(key, -1)
if v != -1:
j = v
break
keys.append(key)
if u < a[j] < d: # if can insert to both
if a[j] < a[j+1]:
u = max(u, a[j])
elif a[j] > a[j+1]:
# TODO: Your code here
elif u < a[j]: # if only can insert to increasing subsequence
u = a[j]
elif d > a[j]: # if only can insert to decreasing subsequence
d = a[j]
else:
break
j += 1
for key in keys:
cache[key] = j
return j
ans = 0
for i in range(n):
u = 0
d = n+1
j = check(i, u, d)
ans += j - i
# print(f'at {i} max {j} ans {ans}', u, d)
# print(f'count={count}')
print(ans)
|
input = __import__('sys').stdin.readline
n = int(input())
a = list(map(int, input().split())) + [n+1]
cache = {}
def check(i, u, d):
keys = []
j = i
while j+1 <= n:
key = (j, u, d)
v = cache.get(key, -1)
if v != -1:
j = v
break
keys.append(key)
if u < a[j] < d: # if can insert to both
if a[j] < a[j+1]:
u = max(u, a[j])
elif a[j] > a[j+1]:
{{completion}}
elif u < a[j]: # if only can insert to increasing subsequence
u = a[j]
elif d > a[j]: # if only can insert to decreasing subsequence
d = a[j]
else:
break
j += 1
for key in keys:
cache[key] = j
return j
ans = 0
for i in range(n):
u = 0
d = n+1
j = check(i, u, d)
ans += j - i
# print(f'at {i} max {j} ans {ans}', u, d)
# print(f'count={count}')
print(ans)
|
d = min(d, a[j])
|
[{"input": "3\n2 3 1", "output": ["6"]}, {"input": "6\n4 5 2 6 1 3", "output": ["19"]}, {"input": "10\n7 10 1 8 3 9 2 4 6 5", "output": ["39"]}]
|
block_completion_000488
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Mihai has an $$$8 \times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 36$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.
Output Specification: For each test case, output two integers $$$r$$$ and $$$c$$$ ($$$2 \leq r, c \leq 7$$$)Β β the row and column of the bishop. The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.
Notes: NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row $$$4$$$ and column $$$3$$$, the correct output is 4 3.
Code:
t = int(input())
for test in range(t):
a = []
while len(a) != 8:
s = input()
if (len(s) == 8):
a.append(s)
x = 0
y = 0
for i in range(1, 7):
for j in range(1, 7):
if (a[i][j] == '#' and a[i-1][j+1] == '#' and a[i-1][j-1] == '#'):
# TODO: Your code here
print(x + 1, y + 1)
|
t = int(input())
for test in range(t):
a = []
while len(a) != 8:
s = input()
if (len(s) == 8):
a.append(s)
x = 0
y = 0
for i in range(1, 7):
for j in range(1, 7):
if (a[i][j] == '#' and a[i-1][j+1] == '#' and a[i-1][j-1] == '#'):
{{completion}}
print(x + 1, y + 1)
|
x = i
y = j
|
[{"input": "3\n\n\n\n\n.....#..\n\n#...#...\n\n.#.#....\n\n..#.....\n\n.#.#....\n\n#...#...\n\n.....#..\n\n......#.\n\n\n\n\n#.#.....\n\n.#......\n\n#.#.....\n\n...#....\n\n....#...\n\n.....#..\n\n......#.\n\n.......#\n\n\n\n\n.#.....#\n\n..#...#.\n\n...#.#..\n\n....#...\n\n...#.#..\n\n..#...#.\n\n.#.....#\n\n#.......", "output": ["4 3\n2 2\n4 5"]}]
|
block_completion_004630
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have an image file of size $$$2 \times 2$$$, consisting of $$$4$$$ pixels. Each pixel can have one of $$$26$$$ different colors, denoted by lowercase Latin letters.You want to recolor some of the pixels of the image so that all $$$4$$$ pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).What is the minimum number of moves you have to make in order to fulfill your goal?
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β the number of test cases. Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.
Output Specification: For each test case, print one integer β the minimum number of moves you have to make so that all $$$4$$$ pixels of the image have the same color.
Notes: NoteLet's analyze the test cases of the example.In the first test case, you can paint the bottom left pixel and the top right pixel (which share the same color) into the color r, so all pixels have this color.In the second test case, two moves are enough: paint both top pixels, which have the same color c, into the color b; paint the bottom left pixel into the color b. In the third test case, all pixels already have the same color.In the fourth test case, you may leave any of the pixels unchanged, and paint all three other pixels into the color of that pixel in three moves.In the fifth test case, you can paint both top pixels into the color x.
Code:
import sys
if __name__ == "__main__":
input_arr = sys.stdin.read().split()
tc = int(input_arr[0])
pos = 1
for case in range(tc):
a1, a2 = input_arr[pos:pos + 2]
char = []
for i in a1:
char.append(i)
for j in a2:
char.append(j)
l = len(set(char))
if l == 4:
print(3)
elif # TODO: Your code here:
print(2)
elif l == 2:
print(1)
elif l == 1:
print(0)
pos += 2
|
import sys
if __name__ == "__main__":
input_arr = sys.stdin.read().split()
tc = int(input_arr[0])
pos = 1
for case in range(tc):
a1, a2 = input_arr[pos:pos + 2]
char = []
for i in a1:
char.append(i)
for j in a2:
char.append(j)
l = len(set(char))
if l == 4:
print(3)
elif {{completion}}:
print(2)
elif l == 2:
print(1)
elif l == 1:
print(0)
pos += 2
|
l == 3
|
[{"input": "5\n\nrb\n\nbr\n\ncc\n\nwb\n\naa\n\naa\n\nab\n\ncd\n\nyy\n\nxx", "output": ["1\n2\n0\n3\n1"]}]
|
control_completion_002660
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \leq i \leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \leq i \leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)?
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) β the elements of the array $$$a$$$.
Output Specification: Print a single integer, the minimum number of moves to make $$$b$$$ increasing.
Notes: NoteExample $$$1$$$: you can subtract $$$a_1$$$ from $$$b_1$$$, and add $$$a_3$$$, $$$a_4$$$, and $$$a_5$$$ to $$$b_3$$$, $$$b_4$$$, and $$$b_5$$$ respectively. The final array will be [$$$-1$$$, $$$0$$$, $$$3$$$, $$$4$$$, $$$5$$$] after $$$4$$$ moves.Example $$$2$$$: you can reach [$$$-3$$$, $$$-2$$$, $$$-1$$$, $$$0$$$, $$$1$$$, $$$2$$$, $$$3$$$] in $$$10$$$ moves.
Code:
import math
n = int(input())
a = list(map(int, input().split(' '))) # numbers w/ ws
c = None
d = 0
for i in range(len(a)):
p = 0
t = 0
for k in a[i+1:]:
d = math.ceil((t+1)/k)
t = k*d
p += d
t = 0
for # TODO: Your code here:
d = math.ceil((t+1)/k)
t = k*d
p += d
if c == None or p < c:
c = p
print(c)
|
import math
n = int(input())
a = list(map(int, input().split(' '))) # numbers w/ ws
c = None
d = 0
for i in range(len(a)):
p = 0
t = 0
for k in a[i+1:]:
d = math.ceil((t+1)/k)
t = k*d
p += d
t = 0
for {{completion}}:
d = math.ceil((t+1)/k)
t = k*d
p += d
if c == None or p < c:
c = p
print(c)
|
k in reversed(a[:i])
|
[{"input": "5\n1 2 3 4 5", "output": ["4"]}, {"input": "7\n1 2 1 2 1 2 1", "output": ["10"]}, {"input": "8\n1 8 2 7 3 6 4 5", "output": ["16"]}]
|
control_completion_000968
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp plays "Rage of Empires II: Definitive Edition" β a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager β a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
Output Specification: Print one integer β the minimum number of onager shots needed to break at least two sections of the wall.
Notes: NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Code:
import sys
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
x, y = sorted(arr)[:2]
ans = (x + 1) // 2 + (y + 1) // 2
for i in range(n - 2):
x, y = arr[i], arr[i + 2]
if (x % 2 == 1) and (y % 2 == 1):
x -= 1
y -= 1
ans = min(ans, (x + 1) // 2 + (y + 1) // 2 + 1)
else:
ans = min(ans, (x + 1) // 2 + (y + 1) // 2)
for i in range(n - 1):
x, y = arr[i], arr[i + 1]
if x > y:
x, y = y, x
if y >= 2 * x:
ans = min(ans, (y + 1) // 2)
else:
# TODO: Your code here
print(ans)
|
import sys
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
x, y = sorted(arr)[:2]
ans = (x + 1) // 2 + (y + 1) // 2
for i in range(n - 2):
x, y = arr[i], arr[i + 2]
if (x % 2 == 1) and (y % 2 == 1):
x -= 1
y -= 1
ans = min(ans, (x + 1) // 2 + (y + 1) // 2 + 1)
else:
ans = min(ans, (x + 1) // 2 + (y + 1) // 2)
for i in range(n - 1):
x, y = arr[i], arr[i + 1]
if x > y:
x, y = y, x
if y >= 2 * x:
ans = min(ans, (y + 1) // 2)
else:
{{completion}}
print(ans)
|
res = y - x
x -= res
y -= 2 * res
tmp = x // 3
res += 2 * tmp
x -= 3 * tmp
ans = min(ans, res + x)
|
[{"input": "5\n20 10 30 10 20", "output": ["10"]}, {"input": "3\n1 8 1", "output": ["1"]}, {"input": "6\n7 6 6 8 5 8", "output": ["4"]}, {"input": "6\n14 3 8 10 15 4", "output": ["4"]}, {"input": "4\n1 100 100 1", "output": ["2"]}, {"input": "3\n40 10 10", "output": ["7"]}]
|
block_completion_007910
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. The $$$i$$$-th column has the bottom $$$a_i$$$ cells blocked (the cells in rows $$$1, 2, \dots, a_i$$$), the remaining $$$n - a_i$$$ cells are unblocked.A robot is travelling across this grid. You can send it commandsΒ β move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.However, the robot is brokenΒ β it executes each received command $$$k$$$ times. So if you tell it to move up, for example, it will move up $$$k$$$ times ($$$k$$$ cells). You can't send it commands while the robot executes the current one.You are asked $$$q$$$ queries about the robot. Each query has a start cell, a finish cell and a value $$$k$$$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times?The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 2 \cdot 10^5$$$)Β β the number of rows and columns of the grid. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$0 \le a_i \le n$$$)Β β the number of blocked cells on the bottom of the $$$i$$$-th column. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$)Β β the number of queries. Each of the next $$$q$$$ lines contain five integers $$$x_s, y_s, x_f, y_f$$$ and $$$k$$$ ($$$a[y_s] < x_s \le n$$$; $$$1 \le y_s \le m$$$; $$$a[y_f] < x_f \le n$$$; $$$1 \le y_f \le m$$$; $$$1 \le k \le 10^9$$$)Β β the row and the column of the start cell, the row and the column of the finish cell and the number of times each your command is executed. The start and the finish cell of each query are unblocked.
Output Specification: For each query, print "YES" if you can send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times. Otherwise, print "NO".
Code:
import sys, collections, math, itertools
input = lambda: sys.stdin.readline().strip()
ints = lambda: list(map(int, input().split()))
Int = lambda: int(input())
n, m = ints()
a = ints()
s = int(m ** .5 + 1)
maxs = [max(a[i:i + s]) for i in range(0, m, s)]
for i in range(Int()):
ys, xs, yf, xf, k = ints()
yes = (xs - xf) % k == 0 and (ys - yf) % k == 0
if # TODO: Your code here:
print('no')
continue
mi, ma = min(xs, xf), max(xs, xf)
high = max([0] + a[mi:min(ma, (mi // s + 1) * s)] + a[max(mi, ma // s * s):ma])
for j in range(min(xs, xf) // s + 1, max(xs, xf) // s):
high = max(high, maxs[j])
if high < ys:
print('yes')
continue
print('yes' if ((high - ys) // k + 1) * k + ys <= n else 'no')
|
import sys, collections, math, itertools
input = lambda: sys.stdin.readline().strip()
ints = lambda: list(map(int, input().split()))
Int = lambda: int(input())
n, m = ints()
a = ints()
s = int(m ** .5 + 1)
maxs = [max(a[i:i + s]) for i in range(0, m, s)]
for i in range(Int()):
ys, xs, yf, xf, k = ints()
yes = (xs - xf) % k == 0 and (ys - yf) % k == 0
if {{completion}}:
print('no')
continue
mi, ma = min(xs, xf), max(xs, xf)
high = max([0] + a[mi:min(ma, (mi // s + 1) * s)] + a[max(mi, ma // s * s):ma])
for j in range(min(xs, xf) // s + 1, max(xs, xf) // s):
high = max(high, maxs[j])
if high < ys:
print('yes')
continue
print('yes' if ((high - ys) // k + 1) * k + ys <= n else 'no')
|
not yes
|
[{"input": "11 10\n9 0 0 10 3 4 8 11 10 8\n6\n1 2 1 3 1\n1 2 1 3 2\n4 3 4 5 2\n5 3 11 5 3\n5 3 11 5 2\n11 9 9 10 1", "output": ["YES\nNO\nNO\nNO\nYES\nYES"]}]
|
control_completion_002939
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $$$5$$$ players in one team for each match). There are $$$N$$$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $$$i$$$-th candidate player has a power of $$$P_i$$$.Pak Chanek will form zero or more teams from the $$$N$$$ candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of $$$D$$$. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is strictly greater than $$$D$$$.One of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.Determine the maximum number of wins that can be achieved by Pak Chanek.
Input Specification: The first line contains two integers $$$N$$$ and $$$D$$$ ($$$1 \le N \le 10^5$$$, $$$1 \le D \le 10^9$$$) β the number of candidate players and the power of the enemy team. The second line contains $$$N$$$ integers $$$P_1, P_2, \ldots, P_N$$$ ($$$1 \le P_i \le 10^9$$$) β the powers of all candidate players.
Output Specification: A line containing an integer representing the maximum number of wins that can be achieved by Pak Chanek.
Notes: NoteThe $$$1$$$-st team formed is a team containing players $$$4$$$ and $$$6$$$. The power of each player in the team becomes $$$100$$$. So the total power of the team is $$$100 + 100 = 200 > 180$$$.The $$$2$$$-nd team formed is a team containing players $$$1$$$, $$$2$$$, and $$$5$$$. The power of each player in the team becomes $$$90$$$. So the total power of the team is $$$90 + 90 + 90 = 270 > 180$$$.
Code:
import math
enemy_power=int(input().split()[1])
team=[int(i) for i in input().split()]
team.sort()
days=0
while len(team)>0:
num=enemy_power//team[-1]+1
if len(team)<num:
break;
else:
# TODO: Your code here
print(days)
|
import math
enemy_power=int(input().split()[1])
team=[int(i) for i in input().split()]
team.sort()
days=0
while len(team)>0:
num=enemy_power//team[-1]+1
if len(team)<num:
break;
else:
{{completion}}
print(days)
|
del team[-1]
del team[0:num-1]
days+=1
|
[{"input": "6 180\n90 80 70 60 50 100", "output": ["2"]}]
|
block_completion_003724
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer β the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
for i in range(int(input())):
data = [[0 for l in range(11)] for k in range(11)]
for j in range(int(input())):
first, second = input()
data[ord(first)-ord('a')][ord(second)-ord('a')] += 1
answer = 0
for j in range(11):
for k in range(11):
for l in range(11):
if j != l:
answer += data[j][k]*data[l][k]
if k != l:
# TODO: Your code here
print(answer//2)
|
for i in range(int(input())):
data = [[0 for l in range(11)] for k in range(11)]
for j in range(int(input())):
first, second = input()
data[ord(first)-ord('a')][ord(second)-ord('a')] += 1
answer = 0
for j in range(11):
for k in range(11):
for l in range(11):
if j != l:
answer += data[j][k]*data[l][k]
if k != l:
{{completion}}
print(answer//2)
|
answer += data[j][k]*data[j][l]
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
block_completion_000884
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if l[cur][2]!=0 or l[cur][1]==l[cur][0]:f=1
if d[l[cur][1]]==2:# TODO: Your code here
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if l[cur][2]!=0 or l[cur][1]==l[cur][0]:f=1
if d[l[cur][1]]==2:{{completion}}
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
break
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006032
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) β the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$) Β β the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.
Notes: NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.
Code:
for _ in range(int(input())):
a,b,ab,ba=map(int,input().split());s=input()
if s.count('A')!=a+ab+ba:print('NO');continue
stack=[[1,s[0]]]
for i in range(1,len(s)):
if stack[-1][1]!=s[i]:
x=stack.pop()
stack.append([x[0]+1,s[i]])
else: stack.append([1,s[i]])
stack.sort();trash=0
for val,ele in stack:
if not val%2:
if ele=='A' and ba>=val//2:ba-=(val//2)
elif ele=='B' and ab>=val//2:ab-=(val//2)
else:# TODO: Your code here
else:
trash+=(val//2)
print('YES' if trash>=ab+ba else 'NO')
|
for _ in range(int(input())):
a,b,ab,ba=map(int,input().split());s=input()
if s.count('A')!=a+ab+ba:print('NO');continue
stack=[[1,s[0]]]
for i in range(1,len(s)):
if stack[-1][1]!=s[i]:
x=stack.pop()
stack.append([x[0]+1,s[i]])
else: stack.append([1,s[i]])
stack.sort();trash=0
for val,ele in stack:
if not val%2:
if ele=='A' and ba>=val//2:ba-=(val//2)
elif ele=='B' and ab>=val//2:ab-=(val//2)
else:{{completion}}
else:
trash+=(val//2)
print('YES' if trash>=ab+ba else 'NO')
|
trash+=(val//2-1)
|
[{"input": "8\n1 0 0 0\nB\n0 0 1 0\nAB\n1 1 0 1\nABAB\n1 0 1 1\nABAAB\n1 1 2 2\nBAABBABBAA\n1 1 2 3\nABABABBAABAB\n2 3 5 4\nAABAABBABAAABABBABBBABB\n1 3 3 10\nBBABABABABBBABABABABABABAABABA", "output": ["NO\nYES\nYES\nYES\nYES\nYES\nNO\nYES"]}]
|
block_completion_001213
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way. Initially, you place block $$$1$$$ at $$$(0, 0)$$$. For $$$2 \le i \le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently: Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output $$$n$$$ integers. The $$$r$$$-th of them should be the maximum size of an tower of color $$$r$$$ you can form by following the given rules. If you cannot form any tower of color $$$r$$$, the $$$r$$$-th integer should be $$$0$$$.
Notes: NoteIn the first test case, one of the possible ways to form a tower of color $$$1$$$ and size $$$3$$$ is: place block $$$1$$$ at position $$$(0, 0)$$$; place block $$$2$$$ to the right of block $$$1$$$, at position $$$(1, 0)$$$; place block $$$3$$$ above block $$$2$$$, at position $$$(1, 1)$$$; place block $$$4$$$ to the left of block $$$3$$$, at position $$$(0, 1)$$$; place block $$$5$$$ to the left of block $$$4$$$, at position $$$(-1, 1)$$$; place block $$$6$$$ above block $$$5$$$, at position $$$(-1, 2)$$$; place block $$$7$$$ to the right of block $$$6$$$, at position $$$(0, 2)$$$. The blocks at positions $$$(0, 0)$$$, $$$(0, 1)$$$, and $$$(0, 2)$$$ all have color $$$1$$$, forming an tower of size $$$3$$$.In the second test case, note that the following placement is not valid, since you are not allowed to place block $$$6$$$ under block $$$5$$$: It can be shown that it is impossible to form a tower of color $$$4$$$ and size $$$3$$$.
Code:
import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]
def next(): return tokens.pop()
def nextInt(): return int(next())
def nextFloat(): return float(next())
def getIntArray(n): return [nextInt() for _ in range(n)]
def getFloatArray(n): return [nextFloat() for _ in range(n)]
def getStringArray(n): return [next() for _ in range(n)]
testcase = True
def solve(testcase = 1):
N = nextInt()
A = getIntArray(N)
map = {}
for i in range(N):
if A[i] not in map: map[A[i]] = []
map[A[i]].append(i)
for color in range(1, N + 1):
if color not in map:
print(0, end=' ')
continue
ar = map[color]
oddCount = evenCount = 0
for i in ar:
if # TODO: Your code here:
evenCount = max(evenCount, oddCount + 1)
else:
oddCount = max(oddCount, evenCount + 1)
print(max(oddCount, evenCount), end=' ')
print()
if testcase is None:
testcaseCount = 1
while tokens:
solve(testcaseCount)
testcaseCount += 1
else:
testcaseCount = nextInt() if testcase else 1
for tc in range(testcaseCount):
solve(tc + 1)
assert not tokens
|
import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]
def next(): return tokens.pop()
def nextInt(): return int(next())
def nextFloat(): return float(next())
def getIntArray(n): return [nextInt() for _ in range(n)]
def getFloatArray(n): return [nextFloat() for _ in range(n)]
def getStringArray(n): return [next() for _ in range(n)]
testcase = True
def solve(testcase = 1):
N = nextInt()
A = getIntArray(N)
map = {}
for i in range(N):
if A[i] not in map: map[A[i]] = []
map[A[i]].append(i)
for color in range(1, N + 1):
if color not in map:
print(0, end=' ')
continue
ar = map[color]
oddCount = evenCount = 0
for i in ar:
if {{completion}}:
evenCount = max(evenCount, oddCount + 1)
else:
oddCount = max(oddCount, evenCount + 1)
print(max(oddCount, evenCount), end=' ')
print()
if testcase is None:
testcaseCount = 1
while tokens:
solve(testcaseCount)
testcaseCount += 1
else:
testcaseCount = nextInt() if testcase else 1
for tc in range(testcaseCount):
solve(tc + 1)
assert not tokens
|
i % 2 == 0
|
[{"input": "6\n\n7\n\n1 2 3 1 2 3 1\n\n6\n\n4 2 2 2 4 4\n\n1\n\n1\n\n5\n\n5 4 5 3 5\n\n6\n\n3 3 3 1 3 3\n\n8\n\n1 2 3 4 4 3 2 1", "output": ["3 2 2 0 0 0 0 \n0 3 0 2 0 0 \n1 \n0 0 1 1 1 \n1 0 4 0 0 0 \n2 2 2 2 0 0 0 0"]}]
|
control_completion_003617
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a string $$$s$$$, consisting of lowercase Latin letters.You are asked $$$q$$$ queries about it: given another string $$$t$$$, consisting of lowercase Latin letters, perform the following steps: concatenate $$$s$$$ and $$$t$$$; calculate the prefix function of the resulting string $$$s+t$$$; print the values of the prefix function on positions $$$|s|+1, |s|+2, \dots, |s|+|t|$$$ ($$$|s|$$$ and $$$|t|$$$ denote the lengths of strings $$$s$$$ and $$$t$$$, respectively); revert the string back to $$$s$$$. The prefix function of a string $$$a$$$ is a sequence $$$p_1, p_2, \dots, p_{|a|}$$$, where $$$p_i$$$ is the maximum value of $$$k$$$ such that $$$k < i$$$ and $$$a[1..k]=a[i-k+1..i]$$$ ($$$a[l..r]$$$ denotes a contiguous substring of a string $$$a$$$ from a position $$$l$$$ to a position $$$r$$$, inclusive). In other words, it's the longest proper prefix of the string $$$a[1..i]$$$ that is equal to its suffix of the same length.
Input Specification: The first line contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 10^6$$$), consisting of lowercase Latin letters. The second line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$)Β β the number of queries. Each of the next $$$q$$$ lines contains a query: a non-empty string $$$t$$$ ($$$1 \le |t| \le 10$$$), consisting of lowercase Latin letters.
Output Specification: For each query, print the values of the prefix function of a string $$$s+t$$$ on positions $$$|s|+1, |s|+2, \dots, |s|+|t|$$$.
Code:
def get_next(j, k, nxt, p):
while p[j] != '$':
if k == -1 or p[j] == p[k]:
j += 1
k += 1
if p[j] == p[k]:
nxt[j] = nxt[k]
else:
# TODO: Your code here
else:
k = nxt[k]
return j, k, nxt
def solve():
s = input().strip()
len_s = len(s)
ns = [ch for ch in s]
for i in range(11):
ns.append('$')
# print(ns)
j, k, nxt = get_next(0, -1, [-1 for i in range(len(ns))], ns)
q = int(input().strip())
for _ in range(q):
t = input().strip()
ans = []
for i in range(10):
ns[i + len_s] = '$'
for i in range(len(t)):
ns[i + len_s] = t[i]
# print(ns)
nj, nk, n_nxt = get_next(j, k, nxt, ns)
# print(n_nxt)
ans.append(n_nxt[len_s + i + 1])
print(' '.join(map(str, ans)))
if __name__ == '__main__':
# t = int(input().strip())
# for _ in range(t):
solve()
|
def get_next(j, k, nxt, p):
while p[j] != '$':
if k == -1 or p[j] == p[k]:
j += 1
k += 1
if p[j] == p[k]:
nxt[j] = nxt[k]
else:
{{completion}}
else:
k = nxt[k]
return j, k, nxt
def solve():
s = input().strip()
len_s = len(s)
ns = [ch for ch in s]
for i in range(11):
ns.append('$')
# print(ns)
j, k, nxt = get_next(0, -1, [-1 for i in range(len(ns))], ns)
q = int(input().strip())
for _ in range(q):
t = input().strip()
ans = []
for i in range(10):
ns[i + len_s] = '$'
for i in range(len(t)):
ns[i + len_s] = t[i]
# print(ns)
nj, nk, n_nxt = get_next(j, k, nxt, ns)
# print(n_nxt)
ans.append(n_nxt[len_s + i + 1])
print(' '.join(map(str, ans)))
if __name__ == '__main__':
# t = int(input().strip())
# for _ in range(t):
solve()
|
nxt[j] = k
|
[{"input": "aba\n6\ncaba\naba\nbababa\naaaa\nb\nforces", "output": ["0 1 2 3 \n1 2 3 \n2 3 4 5 6 7 \n1 1 1 1 \n2 \n0 0 0 0 0 0"]}, {"input": "aacba\n4\naaca\ncbbb\naab\nccaca", "output": ["2 2 3 1 \n0 0 0 0 \n2 2 0 \n0 0 1 0 1"]}]
|
block_completion_002698
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
Input Specification: The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ Β β the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ Β β the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
Code:
import sys
input=sys.stdin.readline
I = lambda : list(map(int,input().split()))
t,=I()
for _ in range(t):
n, = I()
l = I()
pos = 0
if sum(l)!=0 or l[-1]>0:
pos=1
else:
pref = l[0]
seen = 0
if pref<0:
pos=1
if pref==0:
seen = 1
for i in range(1,n):
pref+=l[i]
if pref<0:
pos=1
break
elif pref==0:
seen = 1
else:
if # TODO: Your code here:
pos=1
break
print("YNeos"[pos::2])
|
import sys
input=sys.stdin.readline
I = lambda : list(map(int,input().split()))
t,=I()
for _ in range(t):
n, = I()
l = I()
pos = 0
if sum(l)!=0 or l[-1]>0:
pos=1
else:
pref = l[0]
seen = 0
if pref<0:
pos=1
if pref==0:
seen = 1
for i in range(1,n):
pref+=l[i]
if pref<0:
pos=1
break
elif pref==0:
seen = 1
else:
if {{completion}}:
pos=1
break
print("YNeos"[pos::2])
|
seen
|
[{"input": "7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0", "output": ["No\nYes\nNo\nNo\nYes\nYes\nYes"]}]
|
control_completion_000427
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Leslie and Leon entered a labyrinth. The labyrinth consists of $$$n$$$ halls and $$$m$$$ one-way passages betweenΒ them. The halls are numbered from $$$1$$$ to $$$n$$$.Leslie and Leon start their journey in the hall $$$s$$$. Right away, they quarrel and decide to explore theΒ labyrinth separately. However, they want to meet again at the end of their journey.To help Leslie and Leon, your task is to find two different paths from the given hall $$$s$$$ to some other hall $$$t$$$, such that these two paths do not share halls other than the staring hall $$$s$$$ and the ending hall $$$t$$$. TheΒ hallΒ $$$t$$$ has not been determined yet, so you can choose any of the labyrinth's halls as $$$t$$$ except $$$s$$$.Leslie's and Leon's paths do not have to be the shortest ones, but their paths must be simple, visiting any hall at most once. Also, they cannot visit any common halls except $$$s$$$ and $$$t$$$ during their journey, even at different times.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$, and $$$s$$$, where $$$n$$$Β ($$$2 \le n \le 2 \cdot 10^5$$$) is the number of vertices, $$$m$$$Β ($$$0 \le m \le 2 \cdot 10^5$$$) is the number of edges in the labyrinth, and $$$s$$$Β ($$$1 \le s \le n$$$) is the starting hall. Then $$$m$$$ lines with descriptions of passages follow. Each description contains two integers $$$u_i$$$,Β $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$), denoting a passage from the hall $$$u_i$$$ to the hall $$$v_i$$$. The passages are one-way. Each tuple $$$(u_i, v_i)$$$ is present in the input at most once. The labyrinth can contain cycles and is not necessarily connected in any way.
Output Specification: If it is possible to find the desired two paths, output "Possible", otherwise output "Impossible". If the answer exists, output two path descriptions. Each description occupies two lines. The first line of the description contains an integer $$$h$$$ ($$$2 \le h \le n$$$)Β β the number of halls in a path, and the second line contains distinct integers $$$w_1, w_2, \dots, w_h$$$ ($$$w_1 = s$$$; $$$1 \le w_j \le n$$$; $$$w_h = t$$$)Β β the halls in the path in the order of passing. Both paths must end at the same vertex $$$t$$$. The paths must be different, and all intermediate halls in these paths must be distinct.
Code:
import collections
def caminho(parent, sala):
resp = []
while sala is not None:
resp.append(sala)
sala = parent[sala]
return list(reversed(resp))
def solve(grafo, total, inicio):
if len(grafo[inicio]) < 2:
return
globalParent = collections.defaultdict(lambda: None)
for sala1 in grafo[inicio]:
currentParent = collections.defaultdict(lambda: None)
currentParent[sala1] = inicio
fila = collections.deque()
fila.append(sala1)
while len(fila) > 0:
y = fila.popleft()
for x in grafo[y]:
if x != inicio and currentParent[x] is None:
# TODO: Your code here
for x in currentParent:
if x in globalParent:
#Deu bom
return (caminho(globalParent, x), caminho(currentParent, x))
for x,y in currentParent.items():
globalParent[x] = y
n, m, s = map(int, input().split())
g = collections.defaultdict(list)
for i in range(m):
x,y = map(int, input().split())
g[x].append(y)
paths = solve(g,n,s)
if paths is None:
print("Impossible")
else:
print("Possible")
for i in paths:
print(len(i))
print(" ".join(map(str,i)))
|
import collections
def caminho(parent, sala):
resp = []
while sala is not None:
resp.append(sala)
sala = parent[sala]
return list(reversed(resp))
def solve(grafo, total, inicio):
if len(grafo[inicio]) < 2:
return
globalParent = collections.defaultdict(lambda: None)
for sala1 in grafo[inicio]:
currentParent = collections.defaultdict(lambda: None)
currentParent[sala1] = inicio
fila = collections.deque()
fila.append(sala1)
while len(fila) > 0:
y = fila.popleft()
for x in grafo[y]:
if x != inicio and currentParent[x] is None:
{{completion}}
for x in currentParent:
if x in globalParent:
#Deu bom
return (caminho(globalParent, x), caminho(currentParent, x))
for x,y in currentParent.items():
globalParent[x] = y
n, m, s = map(int, input().split())
g = collections.defaultdict(list)
for i in range(m):
x,y = map(int, input().split())
g[x].append(y)
paths = solve(g,n,s)
if paths is None:
print("Impossible")
else:
print("Possible")
for i in paths:
print(len(i))
print(" ".join(map(str,i)))
|
currentParent[x] = y
fila.append(x)
|
[{"input": "5 5 1\n1 2\n2 3\n1 4\n4 3\n3 5", "output": ["Possible\n3\n1 2 3\n3\n1 4 3"]}, {"input": "5 5 1\n1 2\n2 3\n3 4\n2 5\n5 4", "output": ["Impossible"]}, {"input": "3 3 2\n1 2\n2 3\n3 1", "output": ["Impossible"]}]
|
block_completion_003160
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are $$$n$$$ students in the class, and you are given an array $$$s$$$ in non-decreasing order, where $$$s_i$$$ is the shoe size of the $$$i$$$-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation $$$p$$$ of $$$\{1,2,\ldots,n\}$$$ denoting a valid shuffling of shoes, where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student ($$$p_i \ne i$$$). And output $$$-1$$$ if a valid shuffling does not exist.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).
Input Specification: Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) β the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq10^5$$$)Β β the number of students. The second line of each test case contains $$$n$$$ integers $$$s_1, s_2,\ldots,s_n$$$ ($$$1\leq s_i\leq10^9$$$, and for all $$$1\le i<n$$$, $$$s_i\le s_{i+1}$$$) β the shoe sizes of the students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print the answer in a single line using the following format. If a valid shuffling does not exist, print the number $$$-1$$$ as the answer. If a valid shuffling exists, print $$$n$$$ space-separated integers β a permutation $$$p$$$ of $$$1,2,\ldots,n$$$ denoting a valid shuffling of shoes where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student. If there are multiple answers, then print any of them.
Notes: NoteIn the first test case, any permutation $$$p$$$ of $$$1,\ldots,n$$$ where $$$p_i\ne i$$$ would represent a valid shuffling since all students have equal shoe sizes, and thus anyone can wear anyone's shoes.In the second test case, it can be shown that no valid shuffling is possible.
Code:
for t in range(int(input())):
n=int(input())
x=list(map(int,input().split()))
g={}
if n==1:
print(-1)
else:
for i in range(n-1):
if not((x[i]==x[i+1] or x[i]==x[i-1]) and ( x[-1]==x[-2])):
print(-1)
break
g[x[i]]=[]
else:
for i in range(n):
g[x[i]].append(i+1)
for i,j in g.items():
for q in range(len(j)):
# TODO: Your code here
print()
|
for t in range(int(input())):
n=int(input())
x=list(map(int,input().split()))
g={}
if n==1:
print(-1)
else:
for i in range(n-1):
if not((x[i]==x[i+1] or x[i]==x[i-1]) and ( x[-1]==x[-2])):
print(-1)
break
g[x[i]]=[]
else:
for i in range(n):
g[x[i]].append(i+1)
for i,j in g.items():
for q in range(len(j)):
{{completion}}
print()
|
print(j[q-1],end=' ')
|
[{"input": "2\n5\n1 1 1 1 1\n6\n3 6 8 13 15 21", "output": ["5 1 2 3 4 \n-1"]}]
|
block_completion_002399
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Codeforces separates its users into $$$4$$$ divisions by their rating: For Division 1: $$$1900 \leq \mathrm{rating}$$$ For Division 2: $$$1600 \leq \mathrm{rating} \leq 1899$$$ For Division 3: $$$1400 \leq \mathrm{rating} \leq 1599$$$ For Division 4: $$$\mathrm{rating} \leq 1399$$$ Given a $$$\mathrm{rating}$$$, print in which division the $$$\mathrm{rating}$$$ belongs.
Input Specification: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) β the number of testcases. The description of each test consists of one line containing one integer $$$\mathrm{rating}$$$ ($$$-5000 \leq \mathrm{rating} \leq 5000$$$).
Output Specification: For each test case, output a single line containing the correct division in the format "Division X", where $$$X$$$ is an integer between $$$1$$$ and $$$4$$$ representing the division for the corresponding rating.
Notes: NoteFor test cases $$$1-4$$$, the corresponding ratings are $$$-789$$$, $$$1299$$$, $$$1300$$$, $$$1399$$$, so all of them are in division $$$4$$$.For the fifth test case, the corresponding rating is $$$1400$$$, so it is in division $$$3$$$.For the sixth test case, the corresponding rating is $$$1679$$$, so it is in division $$$2$$$.For the seventh test case, the corresponding rating is $$$2300$$$, so it is in division $$$1$$$.
Code:
k = 0
a = int(input())
for x in range(1, a+1):
b = int(input())
if 1900<= b:
d = 1
elif 1600 <= b <= 1899:
d = 2
elif 1400 <= b <= 1599:
# TODO: Your code here
elif b <= 1399:
d = 4
print('Division', d)
|
k = 0
a = int(input())
for x in range(1, a+1):
b = int(input())
if 1900<= b:
d = 1
elif 1600 <= b <= 1899:
d = 2
elif 1400 <= b <= 1599:
{{completion}}
elif b <= 1399:
d = 4
print('Division', d)
|
d = 3
|
[{"input": "7\n-789\n1299\n1300\n1399\n1400\n1679\n2300", "output": ["Division 4\nDivision 4\nDivision 4\nDivision 4\nDivision 3\nDivision 2\nDivision 1"]}]
|
block_completion_000734
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Leslie and Leon entered a labyrinth. The labyrinth consists of $$$n$$$ halls and $$$m$$$ one-way passages betweenΒ them. The halls are numbered from $$$1$$$ to $$$n$$$.Leslie and Leon start their journey in the hall $$$s$$$. Right away, they quarrel and decide to explore theΒ labyrinth separately. However, they want to meet again at the end of their journey.To help Leslie and Leon, your task is to find two different paths from the given hall $$$s$$$ to some other hall $$$t$$$, such that these two paths do not share halls other than the staring hall $$$s$$$ and the ending hall $$$t$$$. TheΒ hallΒ $$$t$$$ has not been determined yet, so you can choose any of the labyrinth's halls as $$$t$$$ except $$$s$$$.Leslie's and Leon's paths do not have to be the shortest ones, but their paths must be simple, visiting any hall at most once. Also, they cannot visit any common halls except $$$s$$$ and $$$t$$$ during their journey, even at different times.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$, and $$$s$$$, where $$$n$$$Β ($$$2 \le n \le 2 \cdot 10^5$$$) is the number of vertices, $$$m$$$Β ($$$0 \le m \le 2 \cdot 10^5$$$) is the number of edges in the labyrinth, and $$$s$$$Β ($$$1 \le s \le n$$$) is the starting hall. Then $$$m$$$ lines with descriptions of passages follow. Each description contains two integers $$$u_i$$$,Β $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$), denoting a passage from the hall $$$u_i$$$ to the hall $$$v_i$$$. The passages are one-way. Each tuple $$$(u_i, v_i)$$$ is present in the input at most once. The labyrinth can contain cycles and is not necessarily connected in any way.
Output Specification: If it is possible to find the desired two paths, output "Possible", otherwise output "Impossible". If the answer exists, output two path descriptions. Each description occupies two lines. The first line of the description contains an integer $$$h$$$ ($$$2 \le h \le n$$$)Β β the number of halls in a path, and the second line contains distinct integers $$$w_1, w_2, \dots, w_h$$$ ($$$w_1 = s$$$; $$$1 \le w_j \le n$$$; $$$w_h = t$$$)Β β the halls in the path in the order of passing. Both paths must end at the same vertex $$$t$$$. The paths must be different, and all intermediate halls in these paths must be distinct.
Code:
def DFS(start):
nodes=set()
stack=[start]
while stack:
parent=stack.pop()
if(not visited[parent]):
nodes.add(parent)
visited[parent]=True
for child in graph[parent]:
if (not visited[child]):
# TODO: Your code here
else:
if child not in nodes and child!=s:
return child
else:
if parent not in nodes and parent != s:
return parent
return -1
def DFS_get_path(start):
stack=[start]
parent_list[start]=-1
while stack:
parent=stack.pop()
if parent==end:
visited[end]=False
return True
if(not visited[parent]):
visited[parent]=True
for child in graph[parent]:
if (not visited[child]):
stack.append(child)
parent_list[child]=parent
return False
def get_path(node):
path=[]
while node!=-1:
path.append(node)
node=parent_list[node]
path.reverse()
return path
n,m,s=map(int,input().split())
s-=1
graph=[[] for _ in range(n)]
for _ in range(m):
a,b=map(int,input().split())
a-=1
b-=1
graph[a].append(b)
visited=[False]*n
visited[s]=True
for child in graph[s]:
end=DFS(child)
if end!=-1:
visited = [False] * n
parent_list=[-1]*n
visited[s]=True
ans=[]
for child in graph[s]:
if DFS_get_path(child):
ans.append([s]+get_path(end))
if len(ans)==2:
break
print("Possible")
for i in ans:
print(len(i))
print(*[j+1 for j in i])
break
else:
print("Impossible")
# 3 3 1
# 1 2
# 2 1
# 1 3
|
def DFS(start):
nodes=set()
stack=[start]
while stack:
parent=stack.pop()
if(not visited[parent]):
nodes.add(parent)
visited[parent]=True
for child in graph[parent]:
if (not visited[child]):
{{completion}}
else:
if child not in nodes and child!=s:
return child
else:
if parent not in nodes and parent != s:
return parent
return -1
def DFS_get_path(start):
stack=[start]
parent_list[start]=-1
while stack:
parent=stack.pop()
if parent==end:
visited[end]=False
return True
if(not visited[parent]):
visited[parent]=True
for child in graph[parent]:
if (not visited[child]):
stack.append(child)
parent_list[child]=parent
return False
def get_path(node):
path=[]
while node!=-1:
path.append(node)
node=parent_list[node]
path.reverse()
return path
n,m,s=map(int,input().split())
s-=1
graph=[[] for _ in range(n)]
for _ in range(m):
a,b=map(int,input().split())
a-=1
b-=1
graph[a].append(b)
visited=[False]*n
visited[s]=True
for child in graph[s]:
end=DFS(child)
if end!=-1:
visited = [False] * n
parent_list=[-1]*n
visited[s]=True
ans=[]
for child in graph[s]:
if DFS_get_path(child):
ans.append([s]+get_path(end))
if len(ans)==2:
break
print("Possible")
for i in ans:
print(len(i))
print(*[j+1 for j in i])
break
else:
print("Impossible")
# 3 3 1
# 1 2
# 2 1
# 1 3
|
stack.append(child)
|
[{"input": "5 5 1\n1 2\n2 3\n1 4\n4 3\n3 5", "output": ["Possible\n3\n1 2 3\n3\n1 4 3"]}, {"input": "5 5 1\n1 2\n2 3\n3 4\n2 5\n5 4", "output": ["Impossible"]}, {"input": "3 3 2\n1 2\n2 3\n3 1", "output": ["Impossible"]}]
|
block_completion_003165
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
Input Specification: The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) β the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' β the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) β the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
Output Specification: Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
Code:
from sys import stdin
rln=stdin.buffer.readline
rl=lambda:rln().rstrip(b'\r\n').rstrip(b'\n')
ri=lambda:int(rln())
rif=lambda:[*map(int,rln().split())]
rt=lambda:rl().decode()
rtf=lambda:rln().decode().split()
inf=float('inf')
dir4=[(-1,0),(0,1),(1,0),(0,-1)]
dir8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
YES,NO,Yes,No,yes,no='YES','NO','Yes','No','yes','no'
m,n,q=rif()
a=[0]*(m*n)
for y in range(m):
s=rt()
for # TODO: Your code here:
a[m*x+y]=s[x]=='*'
k=sum(a)
l=sum(a[:k])
for _ in range(q):
x,y=rif()
x,y=x-1,y-1
i=x+m*y
if a[i]:
k-=1
l-=a[k]
l-=i<k
a[i]^=1
else:
a[i]^=1
l+=i<k
l+=a[k]
k+=1
print(k-l)
|
from sys import stdin
rln=stdin.buffer.readline
rl=lambda:rln().rstrip(b'\r\n').rstrip(b'\n')
ri=lambda:int(rln())
rif=lambda:[*map(int,rln().split())]
rt=lambda:rl().decode()
rtf=lambda:rln().decode().split()
inf=float('inf')
dir4=[(-1,0),(0,1),(1,0),(0,-1)]
dir8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
YES,NO,Yes,No,yes,no='YES','NO','Yes','No','yes','no'
m,n,q=rif()
a=[0]*(m*n)
for y in range(m):
s=rt()
for {{completion}}:
a[m*x+y]=s[x]=='*'
k=sum(a)
l=sum(a[:k])
for _ in range(q):
x,y=rif()
x,y=x-1,y-1
i=x+m*y
if a[i]:
k-=1
l-=a[k]
l-=i<k
a[i]^=1
else:
a[i]^=1
l+=i<k
l+=a[k]
k+=1
print(k-l)
|
x in range(n)
|
[{"input": "4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "output": ["3\n4\n4\n3\n4\n5\n5\n5"]}, {"input": "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3", "output": ["2\n3\n3\n3\n2"]}]
|
control_completion_007737
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 1 << ADDRESS_BITS_PER_WORD
MASK = -0x1
MASK_MAX = 0x7fffffffffffffff
MASK_MIN = ~MASK_MAX
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def _shift_one_left(self, shift):
if shift == BitSet.WORD_SZ - 1:
return BitSet.MASK_MIN
return 1 << (shift % BitSet.WORD_SZ)
def _shift_mask_right(self, shift):
if shift == 0:
return BitSet.MASK
return BitSet.MASK_MAX >> (shift - 1)
def _shift_mask_left(self, shift):
if shift == 0:
return BitSet.MASK
return ~(BitSet.MASK_MAX >> (BitSet.WORD_SZ - shift - 1))
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if # TODO: Your code here:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex]
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = ~self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex]
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 1 << ADDRESS_BITS_PER_WORD
MASK = -0x1
MASK_MAX = 0x7fffffffffffffff
MASK_MIN = ~MASK_MAX
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def _shift_one_left(self, shift):
if shift == BitSet.WORD_SZ - 1:
return BitSet.MASK_MIN
return 1 << (shift % BitSet.WORD_SZ)
def _shift_mask_right(self, shift):
if shift == 0:
return BitSet.MASK
return BitSet.MASK_MAX >> (shift - 1)
def _shift_mask_left(self, shift):
if shift == 0:
return BitSet.MASK
return ~(BitSet.MASK_MAX >> (BitSet.WORD_SZ - shift - 1))
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if {{completion}}:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex]
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = ~self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex]
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
word != 0
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
control_completion_005834
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Leslie and Leon entered a labyrinth. The labyrinth consists of $$$n$$$ halls and $$$m$$$ one-way passages betweenΒ them. The halls are numbered from $$$1$$$ to $$$n$$$.Leslie and Leon start their journey in the hall $$$s$$$. Right away, they quarrel and decide to explore theΒ labyrinth separately. However, they want to meet again at the end of their journey.To help Leslie and Leon, your task is to find two different paths from the given hall $$$s$$$ to some other hall $$$t$$$, such that these two paths do not share halls other than the staring hall $$$s$$$ and the ending hall $$$t$$$. TheΒ hallΒ $$$t$$$ has not been determined yet, so you can choose any of the labyrinth's halls as $$$t$$$ except $$$s$$$.Leslie's and Leon's paths do not have to be the shortest ones, but their paths must be simple, visiting any hall at most once. Also, they cannot visit any common halls except $$$s$$$ and $$$t$$$ during their journey, even at different times.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$, and $$$s$$$, where $$$n$$$Β ($$$2 \le n \le 2 \cdot 10^5$$$) is the number of vertices, $$$m$$$Β ($$$0 \le m \le 2 \cdot 10^5$$$) is the number of edges in the labyrinth, and $$$s$$$Β ($$$1 \le s \le n$$$) is the starting hall. Then $$$m$$$ lines with descriptions of passages follow. Each description contains two integers $$$u_i$$$,Β $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$), denoting a passage from the hall $$$u_i$$$ to the hall $$$v_i$$$. The passages are one-way. Each tuple $$$(u_i, v_i)$$$ is present in the input at most once. The labyrinth can contain cycles and is not necessarily connected in any way.
Output Specification: If it is possible to find the desired two paths, output "Possible", otherwise output "Impossible". If the answer exists, output two path descriptions. Each description occupies two lines. The first line of the description contains an integer $$$h$$$ ($$$2 \le h \le n$$$)Β β the number of halls in a path, and the second line contains distinct integers $$$w_1, w_2, \dots, w_h$$$ ($$$w_1 = s$$$; $$$1 \le w_j \le n$$$; $$$w_h = t$$$)Β β the halls in the path in the order of passing. Both paths must end at the same vertex $$$t$$$. The paths must be different, and all intermediate halls in these paths must be distinct.
Code:
import re
import sys
exit=sys.exit
from bisect import *
from collections import *
ddict=defaultdict
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
rb=lambda:list(map(int,rl()))
rfs=lambda:rln().split()
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rl=lambda:rln().rstrip('\n')
rln=sys.stdin.readline
cat=''.join
catn='\n'.join
mod=1000000007
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
YES,NO,Yes,No,yes,no='YES','NO','Yes','No','yes','no'
########################################################################
n,m,s=ris()
adj=[[] for _ in range(n+1)]
for _ in range(m):
u,v=ris()
adj[u].append(v)
vis=[{} for _ in range(n+1)]
for i in adj[s]:
stk=[i]
vis[s][i]=0
vis[i][i]=s
while stk:
u=stk.pop()
if 1<len(vis[u]):
print('Possible')
for j in vis[u]:
x,path=u,[]
while j in vis[x]:
# TODO: Your code here
print(len(path))
print(*reversed(path))
exit()
for v in adj[u]:
if i in vis[v] or v==s:
continue
stk.append(v)
vis[v][i]=u
print('Impossible')
|
import re
import sys
exit=sys.exit
from bisect import *
from collections import *
ddict=defaultdict
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
rb=lambda:list(map(int,rl()))
rfs=lambda:rln().split()
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rl=lambda:rln().rstrip('\n')
rln=sys.stdin.readline
cat=''.join
catn='\n'.join
mod=1000000007
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
YES,NO,Yes,No,yes,no='YES','NO','Yes','No','yes','no'
########################################################################
n,m,s=ris()
adj=[[] for _ in range(n+1)]
for _ in range(m):
u,v=ris()
adj[u].append(v)
vis=[{} for _ in range(n+1)]
for i in adj[s]:
stk=[i]
vis[s][i]=0
vis[i][i]=s
while stk:
u=stk.pop()
if 1<len(vis[u]):
print('Possible')
for j in vis[u]:
x,path=u,[]
while j in vis[x]:
{{completion}}
print(len(path))
print(*reversed(path))
exit()
for v in adj[u]:
if i in vis[v] or v==s:
continue
stk.append(v)
vis[v][i]=u
print('Impossible')
|
path.append(x)
x=vis[x][j]
|
[{"input": "5 5 1\n1 2\n2 3\n1 4\n4 3\n3 5", "output": ["Possible\n3\n1 2 3\n3\n1 4 3"]}, {"input": "5 5 1\n1 2\n2 3\n3 4\n2 5\n5 4", "output": ["Impossible"]}, {"input": "3 3 2\n1 2\n2 3\n3 1", "output": ["Impossible"]}]
|
block_completion_003163
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$)Β β the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.
Output Specification: Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.
Code:
n,m=map(int,input().split())
world=['x']+list(map(int,input().split()))
L1=[0]
L2=[0]
for i in range(1,n):
L1.append(L1[i-1]+max(world[i]-world[i+1],0))
L2.append(L2[i-1]+max(world[i+1]-world[i],0))
for i in range(m):
s,t=map(int,input().split())
if # TODO: Your code here:
print(L1[t-1]-L1[s-1])
else:
print(L2[s-1]-L2[t-1])
|
n,m=map(int,input().split())
world=['x']+list(map(int,input().split()))
L1=[0]
L2=[0]
for i in range(1,n):
L1.append(L1[i-1]+max(world[i]-world[i+1],0))
L2.append(L2[i-1]+max(world[i+1]-world[i],0))
for i in range(m):
s,t=map(int,input().split())
if {{completion}}:
print(L1[t-1]-L1[s-1])
else:
print(L2[s-1]-L2[t-1])
|
s<t
|
[{"input": "7 6\n10 8 9 6 8 12 7\n1 2\n1 7\n4 6\n7 1\n3 5\n4 2", "output": ["2\n10\n0\n7\n3\n1"]}]
|
control_completion_002893
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
continue
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
# TODO: Your code here
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
continue
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
{{completion}}
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
continue
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005668
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array $$$[1, 1, 1]$$$ is $$$1$$$; $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$; $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.
Input Specification: In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).
Output Specification: Print the answer to each query on a new line.
Notes: NoteAfter the first query $$$a$$$ is equal to $$$[1, 2, 2, 4, 5]$$$, and the answer is $$$29$$$ because we can split each of the subsegments the following way: $$$[1; 1]$$$: $$$[1]$$$, 1 block; $$$[1; 2]$$$: $$$[1] + [2]$$$, 2 blocks; $$$[1; 3]$$$: $$$[1] + [2, 2]$$$, 2 blocks; $$$[1; 4]$$$: $$$[1] + [2, 2] + [4]$$$, 3 blocks; $$$[1; 5]$$$: $$$[1] + [2, 2] + [4] + [5]$$$, 4 blocks; $$$[2; 2]$$$: $$$[2]$$$, 1 block; $$$[2; 3]$$$: $$$[2, 2]$$$, 1 block; $$$[2; 4]$$$: $$$[2, 2] + [4]$$$, 2 blocks; $$$[2; 5]$$$: $$$[2, 2] + [4] + [5]$$$, 3 blocks; $$$[3; 3]$$$: $$$[2]$$$, 1 block; $$$[3; 4]$$$: $$$[2] + [4]$$$, 2 blocks; $$$[3; 5]$$$: $$$[2] + [4] + [5]$$$, 3 blocks; $$$[4; 4]$$$: $$$[4]$$$, 1 block; $$$[4; 5]$$$: $$$[4] + [5]$$$, 2 blocks; $$$[5; 5]$$$: $$$[5]$$$, 1 block; which is $$$1 + 2 + 2 + 3 + 4 + 1 + 1 + 2 + 3 + 1 + 2 + 3 + 1 + 2 + 1 = 29$$$ in total.
Code:
"""
author: Manoj
inp_start
5 5
1 2 3 4 5
3 2
4 2
3 1
2 1
2 2
inp_end
"""
n, m = list(map(int, input().split()))
li = list(map(int, input().split()))
ans = int((n*(n+1))/2)
for i in range(1, n):
if li[i]!=li[i-1]:
ans += i*(n-i)
al = []
for tc in range(m):
i, x = list(map(int, input().split()))
i -= 1
if i>0:
if li[i]!=li[i-1]:
# TODO: Your code here
if x!=li[i-1]:
ans+=i*(n-i)
if i+1<n:
if li[i]!=li[i+1]:
ans-=(i+1)*(n-i-1)
if x!=li[i+1]:
ans+=(i+1)*(n-i-1)
li[i]=x
al.append(ans)
print(*al)
|
"""
author: Manoj
inp_start
5 5
1 2 3 4 5
3 2
4 2
3 1
2 1
2 2
inp_end
"""
n, m = list(map(int, input().split()))
li = list(map(int, input().split()))
ans = int((n*(n+1))/2)
for i in range(1, n):
if li[i]!=li[i-1]:
ans += i*(n-i)
al = []
for tc in range(m):
i, x = list(map(int, input().split()))
i -= 1
if i>0:
if li[i]!=li[i-1]:
{{completion}}
if x!=li[i-1]:
ans+=i*(n-i)
if i+1<n:
if li[i]!=li[i+1]:
ans-=(i+1)*(n-i-1)
if x!=li[i+1]:
ans+=(i+1)*(n-i-1)
li[i]=x
al.append(ans)
print(*al)
|
ans-=i*(n-i)
|
[{"input": "5 5\n1 2 3 4 5\n3 2\n4 2\n3 1\n2 1\n2 2", "output": ["29\n23\n35\n25\n35"]}]
|
block_completion_000083
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes β with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w < n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w < n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ β is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$)Β β $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
Notes: NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Code:
from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List
def solve() -> None:
a = [int(c) % 9 for c in next_token()]
n = len(a)
sa = list(a)
for i in range(1, n):
sa[i] += sa[i - 1]
w = next_int()
indices = defaultdict(list)
for i in range(w, n + 1):
vlr = ((sa[i - 1] - (sa[i - w - 1] if i - w > 0 else 0)) % 9 + 9) % 9
indices[vlr].append(i - w + 1)
cache = dict()
INF = (n + 1, n)
for _ in range(next_int()):
l = next_int() - 1
r = next_int() - 1
k = next_int()
vlr = ((sa[r] - (sa[l - 1] if l > 0 else 0)) % 9 + 9) % 9
if (vlr, k) not in cache:
res = INF
for v1 in range(9):
for v2 in range(9):
if ((v1 * vlr + v2) % 9 + 9) % 9 == k:
if v1 == v2:
if # TODO: Your code here:
res = min(res, tuple(indices[v1][:2]))
else:
if len(indices[v1]) > 0 and len(indices[v2]) > 0:
res = min(res, (indices[v1][0], indices[v2][0]))
cache[(vlr, k)] = res if res != INF else (-1, -1)
print(*cache[(vlr, k)])
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List
def solve() -> None:
a = [int(c) % 9 for c in next_token()]
n = len(a)
sa = list(a)
for i in range(1, n):
sa[i] += sa[i - 1]
w = next_int()
indices = defaultdict(list)
for i in range(w, n + 1):
vlr = ((sa[i - 1] - (sa[i - w - 1] if i - w > 0 else 0)) % 9 + 9) % 9
indices[vlr].append(i - w + 1)
cache = dict()
INF = (n + 1, n)
for _ in range(next_int()):
l = next_int() - 1
r = next_int() - 1
k = next_int()
vlr = ((sa[r] - (sa[l - 1] if l > 0 else 0)) % 9 + 9) % 9
if (vlr, k) not in cache:
res = INF
for v1 in range(9):
for v2 in range(9):
if ((v1 * vlr + v2) % 9 + 9) % 9 == k:
if v1 == v2:
if {{completion}}:
res = min(res, tuple(indices[v1][:2]))
else:
if len(indices[v1]) > 0 and len(indices[v2]) > 0:
res = min(res, (indices[v1][0], indices[v2][0]))
cache[(vlr, k)] = res if res != INF else (-1, -1)
print(*cache[(vlr, k)])
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
len(indices[v1]) > 1
|
[{"input": "5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6", "output": ["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]}]
|
control_completion_008511
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ of $$$n$$$ integers. Initially there is only one copy of the given array.You can do operations of two types: Choose any array and clone it. After that there is one more copy of the chosen array. Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case output a single integerΒ β the minimal number of operations needed to create at least one copy where all elements are equal.
Notes: NoteIn the first test case all elements in the array are already equal, that's why the answer is $$$0$$$.In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:$$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$After that we can swap elements in a way so all zeroes are in one array:$$$[ \ 0 \ \underline{0} \ \underline{0} \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ \underline{1} \ 1 \ 3 \ 3 \ 7 \ \underline{3} \ ]$$$Now let's create a copy of the first array:$$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$, $$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$Let's swap elements in the first two copies:$$$[ \ 0 \ 0 \ 0 \ \underline{0} \ \underline{0} \ 0 \ ]$$$, $$$[ \ \underline{3} \ \underline{7} \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$.Finally, we made a copy where all elements are equal and made $$$6$$$ operations.It can be proven that no fewer operations are enough.
Code:
from collections import Counter
for _ in range(int(input())):
n = int(input())
m = max(Counter(input().split()).values())
ans = n-m
while m<n:
# TODO: Your code here
print(ans)
|
from collections import Counter
for _ in range(int(input())):
n = int(input())
m = max(Counter(input().split()).values())
ans = n-m
while m<n:
{{completion}}
print(ans)
|
ans += 1
m *= 2
|
[{"input": "6\n1\n1789\n6\n0 1 3 3 7 0\n2\n-1000000000 1000000000\n4\n4 3 2 1\n5\n2 5 7 6 3\n7\n1 1 1 1 1 1 1", "output": ["0\n6\n2\n5\n7\n0"]}]
|
block_completion_004419
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$. Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) Β β the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) β the initial levels of trees moisture. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.
Output Specification: For each test case output a single integer β the minimum number of actions. It can be shown that the answer exists.
Notes: NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.
Code:
import sys
T = int(sys.stdin.readline())
for t in range(T):
n = int(sys.stdin.readline())
a = [int(x) for x in sys.stdin.readline().strip().split(' ')]
l, r = 0, 0
for i in range(len(a) - 1):
x, y = a[i], a[i+1]
if x > y:
l += x - y
elif x < y:
# TODO: Your code here
print(abs(a[-1]-r)+l+r)
# 4
# 3
# -2 -2 -2
# 3
# 10 4 7
# 4
# 4 -4 4 -4
# 5
# 1 -2 3 -4 5
|
import sys
T = int(sys.stdin.readline())
for t in range(T):
n = int(sys.stdin.readline())
a = [int(x) for x in sys.stdin.readline().strip().split(' ')]
l, r = 0, 0
for i in range(len(a) - 1):
x, y = a[i], a[i+1]
if x > y:
l += x - y
elif x < y:
{{completion}}
print(abs(a[-1]-r)+l+r)
# 4
# 3
# -2 -2 -2
# 3
# 10 4 7
# 4
# 4 -4 4 -4
# 5
# 1 -2 3 -4 5
|
r += y - x
|
[{"input": "4\n3\n-2 -2 -2\n3\n10 4 7\n4\n4 -4 4 -4\n5\n1 -2 3 -4 5", "output": ["2\n13\n36\n33"]}]
|
block_completion_004205
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$Β β the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.
Input Specification: The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$)Β β elements of given array.
Output Specification: In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.
Notes: NoteIn the first example $$$3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24$$$. Number $$$24$$$ is divisible by $$$4! = 24$$$.In the second example $$$3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18$$$, is divisible by $$$3! = 6$$$.In the third example $$$7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!$$$. It is easy to prove that this number is not divisible by $$$8!$$$.
Code:
n , x = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
s = [0] * (x+1)
for i in l:
s[i] += 1
for i in range(1,x):
if # TODO: Your code here:
s[i+1] += s[i]//(i+1)
else:
print('NO')
break
else:
print('Yes')
|
n , x = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
s = [0] * (x+1)
for i in l:
s[i] += 1
for i in range(1,x):
if {{completion}}:
s[i+1] += s[i]//(i+1)
else:
print('NO')
break
else:
print('Yes')
|
s[i] % (i+1) == 0
|
[{"input": "6 4\n3 2 2 2 3 3", "output": ["Yes"]}, {"input": "8 3\n3 2 2 2 2 2 1 1", "output": ["Yes"]}, {"input": "7 8\n7 7 7 7 7 7 7", "output": ["No"]}, {"input": "10 5\n4 3 2 1 4 3 2 4 3 4", "output": ["No"]}, {"input": "2 500000\n499999 499999", "output": ["No"]}]
|
control_completion_005988
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
n = int(input())
for i in range(n):
str1 = input()
set_char = set(str1)
req = len(set_char)
prev = dict()
truth = True
ind = 0
for i1 in str1:
if# TODO: Your code here:
truth = False
break
prev[i1] = ind
ind += 1
print(truth and 'YES' or 'NO')
|
n = int(input())
for i in range(n):
str1 = input()
set_char = set(str1)
req = len(set_char)
prev = dict()
truth = True
ind = 0
for i1 in str1:
if{{completion}}:
truth = False
break
prev[i1] = ind
ind += 1
print(truth and 'YES' or 'NO')
|
( i1 in prev and ind - prev[i1] != req)
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
control_completion_004714
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i > 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i < i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty): Choose a card $$$x$$$ such that no other cards are hanging onto it. Append the number written on card $$$x$$$ to the end of $$$s$$$. If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$. Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) β the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) describing which card that each card hangs onto.
Output Specification: Print a single integer β the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.
Notes: NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order: Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 > w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$. Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$. Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$. Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 > w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$. Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$. Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.
Code:
n = int(input())
a = [*map(lambda x:int(x)-1,input().split())]
edge = [[] for _ in range(n)]
for i,p in enumerate(a,1): edge[p] += i,
dp = [[1,0] for _ in range(n)]
for r in range(n-1,-1,-1):
for # TODO: Your code here:
k = max(dp[v])
dp[r][1] += k
dp[r][0] = max(dp[r][0],dp[v][0]+1)
print(max(dp[0]))
|
n = int(input())
a = [*map(lambda x:int(x)-1,input().split())]
edge = [[] for _ in range(n)]
for i,p in enumerate(a,1): edge[p] += i,
dp = [[1,0] for _ in range(n)]
for r in range(n-1,-1,-1):
for {{completion}}:
k = max(dp[v])
dp[r][1] += k
dp[r][0] = max(dp[r][0],dp[v][0]+1)
print(max(dp[0]))
|
v in edge[r]
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
control_completion_004638
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns with each cell having a non-negative integer written on it. Timur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is maximal. The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. Help him find the maximal sum he can get.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 200$$$, $$$1 \leq m \leq 200$$$). The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element of the $$$i$$$-th line $$$a_{ij}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row $$$(0\leq a_{ij} \leq 10^6)$$$ It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$4\cdot10^4$$$.
Output Specification: For each test case output a single integer, the maximum sum over all possible placements of the bishop.
Notes: NoteFor the first test case here the best sum is achieved by the bishop being in this position:
Code:
T = int(input())
for tc in range(T):
(A, B) = map(int, input().split(' '))
nums = []
for i in range(A):
nums.append([int(x) for x in input().split()])
C = A + B - 1
left = [0 for _ in range(C)]
right = [0 for _ in range(C)]
for a in range(A):
for # TODO: Your code here:
left_index = a + b
right_index = a + B - 1 - b
left[left_index] += nums[a][b]
right[right_index] += nums[a][b]
# print (left)
# print (right)
damage = 0
for a in range(A):
for b in range(B):
left_index = a + b
right_index = a + B - 1 - b
d = left[left_index] + right[right_index] - nums[a][b]
damage = max(d, damage)
print (damage)
|
T = int(input())
for tc in range(T):
(A, B) = map(int, input().split(' '))
nums = []
for i in range(A):
nums.append([int(x) for x in input().split()])
C = A + B - 1
left = [0 for _ in range(C)]
right = [0 for _ in range(C)]
for a in range(A):
for {{completion}}:
left_index = a + b
right_index = a + B - 1 - b
left[left_index] += nums[a][b]
right[right_index] += nums[a][b]
# print (left)
# print (right)
damage = 0
for a in range(A):
for b in range(B):
left_index = a + b
right_index = a + B - 1 - b
d = left[left_index] + right[right_index] - nums[a][b]
damage = max(d, damage)
print (damage)
|
b in range(B)
|
[{"input": "4\n4 4\n1 2 2 1\n2 4 2 4\n2 2 3 1\n2 4 2 4\n2 1\n1\n0\n3 3\n1 1 1\n1 1 1\n1 1 1\n3 3\n0 1 1\n1 0 1\n1 1 0", "output": ["20\n1\n5\n3"]}]
|
control_completion_007557
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer β the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
for ii in range(int(input())):
n=int(input())
a=[]
co=0
x=set()
for jj in range(n):
a.append(input())
for jj in range(n):
mul=1
if jj not in x:
for kk in range(jj+1,n):
if a[jj][0]!=a[kk][0] and a[jj][1]==a[kk][1]:
co+=mul
elif # TODO: Your code here:
co+=mul
elif a[jj][0]==a[kk][0] and a[jj][1]==a[kk][1]:
mul+=1
x.add(kk)
print(co)
|
for ii in range(int(input())):
n=int(input())
a=[]
co=0
x=set()
for jj in range(n):
a.append(input())
for jj in range(n):
mul=1
if jj not in x:
for kk in range(jj+1,n):
if a[jj][0]!=a[kk][0] and a[jj][1]==a[kk][1]:
co+=mul
elif {{completion}}:
co+=mul
elif a[jj][0]==a[kk][0] and a[jj][1]==a[kk][1]:
mul+=1
x.add(kk)
print(co)
|
a[jj][0]==a[kk][0] and a[jj][1]!=a[kk][1]
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
control_completion_000871
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$You can apply the following operation an arbitrary number of times: select an index $$$i$$$ ($$$1 \le i \le n$$$) and replace the value of the element $$$a_i$$$ with the value $$$a_i + (a_i \bmod 10)$$$, where $$$a_i \bmod 10$$$ is the remainder of the integer dividing $$$a_i$$$ by $$$10$$$. For a single index (value $$$i$$$), this operation can be applied multiple times. If the operation is applied repeatedly to the same index, then the current value of $$$a_i$$$ is taken into account each time. For example, if $$$a_i=47$$$ then after the first operation we get $$$a_i=47+7=54$$$, and after the second operation we get $$$a_i=54+4=58$$$.Check if it is possible to make all array elements equal by applying multiple (possibly zero) operations.For example, you have an array $$$[6, 11]$$$. Let's apply this operation to the first element of the array. Let's replace $$$a_1 = 6$$$ with $$$a_1 + (a_1 \bmod 10) = 6 + (6 \bmod 10) = 6 + 6 = 12$$$. We get the array $$$[12, 11]$$$. Then apply this operation to the second element of the array. Let's replace $$$a_2 = 11$$$ with $$$a_2 + (a_2 \bmod 10) = 11 + (11 \bmod 10) = 11 + 1 = 12$$$. We get the array $$$[12, 12]$$$. Thus, by applying $$$2$$$ operations, you can make all elements of an array equal.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. What follows is a description of each test case. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$)Β β the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \le a_i \le 10^9$$$)Β β array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case print: YES if it is possible to make all array elements equal; NO otherwise. You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer) .
Notes: NoteThe first test case is clarified above.In the second test case, it is impossible to make all array elements equal.In the third test case, you need to apply this operation once to all elements equal to $$$5$$$.In the fourth test case, you need to apply this operation to all elements until they become equal to $$$8$$$.In the fifth test case, it is impossible to make all array elements equal.In the sixth test case, you need to apply this operation to all elements until they become equal to $$$102$$$.
Code:
# Problem - https://codeforces.com/contest/1714/problem/E
# Editorial - https://codeforces.com/blog/entry/105549
# Tags - brute force, math, number theory, *1400
import sys
import typing
# Read stdin and remove newline elements
stdin = [line.strip() for line in sys.stdin.readlines() if line != '\n']
stdin_counter = 0
cycle_for_2 = 20 # 2 => 2 + 2 => 4 + 4 => 8 + 8 => 16 + 6 => 22 - 2 = 20
def take_from_stdin():
global stdin_counter
result = stdin[stdin_counter]
stdin_counter += 1
return result
def solve(arr: typing.List[int]):
has_2 = False
has_0 = False
for i in range(len(arr)):
mod_10 = arr[i] % 10
if mod_10 == 2:
has_2 = True
if mod_10 == 0:
has_0 = True
while mod_10 != 2 and mod_10 != 0:
arr[i] += mod_10
mod_10 = arr[i] % 10
if mod_10 == 2:
# TODO: Your code here
if mod_10 == 0:
has_0 = True
if has_0 and has_2:
return "NO"
if has_2:
for i in range(len(arr)):
arr[i] = arr[i] % 20
if len(set(arr)) == 1:
return "YES"
return "NO"
def main():
test_count = int(take_from_stdin())
for _ in range(test_count):
_ = int(take_from_stdin())
arr = [int(x) for x in take_from_stdin().split()]
print(solve(arr))
main()
|
# Problem - https://codeforces.com/contest/1714/problem/E
# Editorial - https://codeforces.com/blog/entry/105549
# Tags - brute force, math, number theory, *1400
import sys
import typing
# Read stdin and remove newline elements
stdin = [line.strip() for line in sys.stdin.readlines() if line != '\n']
stdin_counter = 0
cycle_for_2 = 20 # 2 => 2 + 2 => 4 + 4 => 8 + 8 => 16 + 6 => 22 - 2 = 20
def take_from_stdin():
global stdin_counter
result = stdin[stdin_counter]
stdin_counter += 1
return result
def solve(arr: typing.List[int]):
has_2 = False
has_0 = False
for i in range(len(arr)):
mod_10 = arr[i] % 10
if mod_10 == 2:
has_2 = True
if mod_10 == 0:
has_0 = True
while mod_10 != 2 and mod_10 != 0:
arr[i] += mod_10
mod_10 = arr[i] % 10
if mod_10 == 2:
{{completion}}
if mod_10 == 0:
has_0 = True
if has_0 and has_2:
return "NO"
if has_2:
for i in range(len(arr)):
arr[i] = arr[i] % 20
if len(set(arr)) == 1:
return "YES"
return "NO"
def main():
test_count = int(take_from_stdin())
for _ in range(test_count):
_ = int(take_from_stdin())
arr = [int(x) for x in take_from_stdin().split()]
print(solve(arr))
main()
|
has_2 = True
|
[{"input": "10\n\n2\n\n6 11\n\n3\n\n2 18 22\n\n5\n\n5 10 5 10 5\n\n4\n\n1 2 4 8\n\n2\n\n4 5\n\n3\n\n93 96 102\n\n2\n\n40 6\n\n2\n\n50 30\n\n2\n\n22 44\n\n2\n\n1 5", "output": ["Yes\nNo\nYes\nYes\nNo\nYes\nNo\nNo\nYes\nNo"]}]
|
block_completion_006707
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
Input Specification: The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)Β β the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$)Β β the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$)Β β the sequence $$$a$$$.
Output Specification: For each test case, print a single integerΒ β the minimum number of operations to change all numbers in the sequence to $$$0$$$.
Notes: NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 < a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Code:
for i in range(int(input())):
n = int(input())
s = input().split()
if s.count("0"):
print(n-s.count("0"))
else:
for i in s:
if # TODO: Your code here:
print(n)
break
else:
print(n+1)
|
for i in range(int(input())):
n = int(input())
s = input().split()
if s.count("0"):
print(n-s.count("0"))
else:
for i in s:
if {{completion}}:
print(n)
break
else:
print(n+1)
|
s.count(i)>1
|
[{"input": "3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0", "output": ["4\n3\n2"]}]
|
control_completion_008025
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 60#1 << ADDRESS_BITS_PER_WORD
MASK = 0xfffffffffffffff
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex // BitSet.WORD_SZ #>> BitSet.ADDRESS_BITS_PER_WORD
def _shift_mask_right(self, shift):
return BitSet.MASK >> shift
def _shift_mask_left(self, shift):
return (BitSet.MASK >> shift) << shift
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.WORD_SZ))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex] & BitSet.MASK
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex] & BitSet.MASK
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
# TODO: Your code here
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 60#1 << ADDRESS_BITS_PER_WORD
MASK = 0xfffffffffffffff
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex // BitSet.WORD_SZ #>> BitSet.ADDRESS_BITS_PER_WORD
def _shift_mask_right(self, shift):
return BitSet.MASK >> shift
def _shift_mask_left(self, shift):
return (BitSet.MASK >> shift) << shift
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.WORD_SZ))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex] & BitSet.MASK
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex] & BitSet.MASK
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
{{completion}}
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (self.sz - i)
break
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005935
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a tree $$$G$$$ with $$$n$$$ vertices and an integer $$$k$$$. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$.For a vertex $$$r$$$ and a subset $$$S$$$ of vertices of $$$G$$$, such that $$$|S| = k$$$, we define $$$f(r, S)$$$ as the size of the smallest rooted subtree containing all vertices in $$$S$$$ when the tree is rooted at $$$r$$$. A set of vertices $$$T$$$ is called a rooted subtree, if all the vertices in $$$T$$$ are connected, and for each vertex in $$$T$$$, all its descendants belong to $$$T$$$.You need to calculate the sum of $$$f(r, S)$$$ over all possible distinct combinations of vertices $$$r$$$ and subsets $$$S$$$, where $$$|S| = k$$$. Formally, compute the following: $$$$$$\sum_{r \in V} \sum_{S \subseteq V, |S| = k} f(r, S),$$$$$$ where $$$V$$$ is the set of vertices in $$$G$$$.Output the answer modulo $$$10^9 + 7$$$.
Input Specification: The first line contains two integers $$$n$$$ and $$$k$$$ ($$$3 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le n$$$). Each of the following $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$), denoting an edge between vertex $$$x$$$ and $$$y$$$. It is guaranteed that the given edges form a tree.
Output Specification: Print the answer modulo $$$10^9 + 7$$$.
Notes: NoteThe tree in the second example is given below: We have $$$21$$$ subsets of size $$$2$$$ in the given tree. Hence, $$$$$$S \in \left\{\{1, 2\}, \{1, 3\}, \{1, 4\}, \{1, 5\}, \{1, 6\}, \{1, 7\}, \{2, 3\}, \{2, 4\}, \{2, 5\}, \{2, 6\}, \{2, 7\}, \{3, 4\}, \{3, 5\}, \{3, 6\}, \{3, 7\}, \{4, 5\}, \{4, 6\}, \{4, 7\}, \{5, 6\}, \{5, 7\}, \{6, 7\} \right\}.$$$$$$ And since we have $$$7$$$ vertices, $$$1 \le r \le 7$$$. We need to find the sum of $$$f(r, S)$$$ over all possible pairs of $$$r$$$ and $$$S$$$. Below we have listed the value of $$$f(r, S)$$$ for some combinations of $$$r$$$ and $$$S$$$. $$$r = 1$$$, $$$S = \{3, 7\}$$$. The value of $$$f(r, S)$$$ is $$$5$$$ and the corresponding subtree is $$$\{2, 3, 4, 6, 7\}$$$. $$$r = 1$$$, $$$S = \{5, 4\}$$$. The value of $$$f(r, S)$$$ is $$$7$$$ and the corresponding subtree is $$$\{1, 2, 3, 4, 5, 6, 7\}$$$. $$$r = 1$$$, $$$S = \{4, 6\}$$$. The value of $$$f(r, S)$$$ is $$$3$$$ and the corresponding subtree is $$$\{4, 6, 7\}$$$.
Code:
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
M = 10 ** 9 + 7
n, k = I()
binomk = [0] * k
binomk.append(1)
for i in range(k + 1, n + 1):
binomk.append(binomk[-1] * i * pow(i - k, M - 2, M) % M)
neighbors = [[] for i in range(n)]
for i in range(n - 1):
a, b = I()
a -= 1
b -= 1
neighbors[a].append(b)
neighbors[b].append(a)
parents = [None] + [-1] * (n - 1)
children = [[] for i in range(n)]
layer = [0]
while layer:
newlayer = []
for guy in layer:
for # TODO: Your code here:
if boi != parents[guy]:
children[guy].append(boi)
parents[boi] = guy
newlayer.append(boi)
layer = newlayer
size = [0] * n
q = []
for i in range(n):
if len(children[i]) == 0:
q.append(i)
qind = 0
left = [len(children[i]) for i in range(n)]
while qind < len(q):
v = q[qind]
tot = 1
for guy in children[v]:
tot += size[guy]
size[v] = tot
if parents[v] is None:
break
left[parents[v]] -= 1
if left[parents[v]] == 0:
q.append(parents[v])
qind += 1
answer = 0
for i in range(n):
things = []
for guy in children[i]:
things.append(size[guy])
if i != 0:
things.append(n - 1 - sum(things))
bins = [binomk[i] for i in things]
ss = sum(bins) % M
for guy in things:
answer = (answer + (n - guy) * guy * binomk[n - guy]) % M
answer = (answer - (n - guy) * guy * (ss - binomk[guy])) % M
answer = (answer + n * binomk[n]) % M
answer = (answer - ss * n) % M
print(answer)
|
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
M = 10 ** 9 + 7
n, k = I()
binomk = [0] * k
binomk.append(1)
for i in range(k + 1, n + 1):
binomk.append(binomk[-1] * i * pow(i - k, M - 2, M) % M)
neighbors = [[] for i in range(n)]
for i in range(n - 1):
a, b = I()
a -= 1
b -= 1
neighbors[a].append(b)
neighbors[b].append(a)
parents = [None] + [-1] * (n - 1)
children = [[] for i in range(n)]
layer = [0]
while layer:
newlayer = []
for guy in layer:
for {{completion}}:
if boi != parents[guy]:
children[guy].append(boi)
parents[boi] = guy
newlayer.append(boi)
layer = newlayer
size = [0] * n
q = []
for i in range(n):
if len(children[i]) == 0:
q.append(i)
qind = 0
left = [len(children[i]) for i in range(n)]
while qind < len(q):
v = q[qind]
tot = 1
for guy in children[v]:
tot += size[guy]
size[v] = tot
if parents[v] is None:
break
left[parents[v]] -= 1
if left[parents[v]] == 0:
q.append(parents[v])
qind += 1
answer = 0
for i in range(n):
things = []
for guy in children[i]:
things.append(size[guy])
if i != 0:
things.append(n - 1 - sum(things))
bins = [binomk[i] for i in things]
ss = sum(bins) % M
for guy in things:
answer = (answer + (n - guy) * guy * binomk[n - guy]) % M
answer = (answer - (n - guy) * guy * (ss - binomk[guy])) % M
answer = (answer + n * binomk[n]) % M
answer = (answer - ss * n) % M
print(answer)
|
boi in neighbors[guy]
|
[{"input": "3 2\n1 2\n1 3", "output": ["25"]}, {"input": "7 2\n1 2\n2 3\n2 4\n1 5\n4 6\n4 7", "output": ["849"]}]
|
control_completion_002442
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
c = list(map(int,sys.stdin.readline().split()))
count = 0
L = [0] * (n+1)
for i in range(0,n):
L[a[i]] = b[i]
status = 1
for i in range(n):
if c[i] != 0:
L[a[i]] = 0
L[b[i]] = 0
for i in range(1,n+1):
key = i
xstatus = 1
status = 1
xcount= 0
while status == 1:
if L[key] == 0:
status = 0
if L[key] == i:
if xcount >= 1:
# TODO: Your code here
status = 0
xcount += 1
x = L[key]
L[key] = 0
key = x
print((2 **count) % (10 ** 9 + 7))
|
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
c = list(map(int,sys.stdin.readline().split()))
count = 0
L = [0] * (n+1)
for i in range(0,n):
L[a[i]] = b[i]
status = 1
for i in range(n):
if c[i] != 0:
L[a[i]] = 0
L[b[i]] = 0
for i in range(1,n+1):
key = i
xstatus = 1
status = 1
xcount= 0
while status == 1:
if L[key] == 0:
status = 0
if L[key] == i:
if xcount >= 1:
{{completion}}
status = 0
xcount += 1
x = L[key]
L[key] = 0
key = x
print((2 **count) % (10 ** 9 + 7))
|
count += 1
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006026
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones and an integer $$$k$$$. In one operation you can do one of the following: Select $$$2$$$ consecutive elements of $$$a$$$ and replace them with their minimum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-1$$$). This operation decreases the size of $$$a$$$ by $$$1$$$. Select $$$k$$$ consecutive elements of $$$a$$$ and replace them with their maximum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \max(a_{i}, a_{i+1}, \ldots, a_{i+k-1}), a_{i+k}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-k+1$$$). This operation decreases the size of $$$a$$$ by $$$k-1$$$. Determine if it's possible to turn $$$a$$$ into $$$[1]$$$ after several (possibly zero) operations.
Input Specification: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 50$$$), the size of array $$$a$$$ and the length of segments that you can perform second type operation on. The second line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$.
Output Specification: For each test case, if it is possible to turn $$$a$$$ into $$$[1]$$$, print "YES", otherwise print "NO".
Notes: NoteIn the first test case, you can perform the second type operation on second and third elements so $$$a$$$ becomes $$$[0, 1]$$$, then you can perform the second type operation on first and second elements, so $$$a$$$ turns to $$$[1]$$$.In the fourth test case, it's obvious to see that you can't make any $$$1$$$, no matter what you do.In the fifth test case, you can first perform a type 2 operation on the first three elements so that $$$a$$$ becomes $$$[1, 0, 0, 1]$$$, then perform a type 2 operation on the elements in positions two through four, so that $$$a$$$ becomes $$$[1, 1]$$$, and finally perform the first type operation on the remaining elements, so that $$$a$$$ becomes $$$[1]$$$.
Code:
from sys import stdin
from collections import deque
lst = list(map(int, stdin.read().split()))
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
# TODO: Your code here
t = inp1()
for _ in range(t):
n = inp1()
k = inp1()
a = set(inp(n))
print("YES" if 1 in a else "NO")
|
from sys import stdin
from collections import deque
lst = list(map(int, stdin.read().split()))
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
{{completion}}
t = inp1()
for _ in range(t):
n = inp1()
k = inp1()
a = set(inp(n))
print("YES" if 1 in a else "NO")
|
return inp()[0]
|
[{"input": "7\n\n3 2\n\n0 1 0\n\n5 3\n\n1 0 1 1 0\n\n2 2\n\n1 1\n\n4 4\n\n0 0 0 0\n\n6 3\n\n0 0 1 0 0 1\n\n7 5\n\n1 1 1 1 1 1 1\n\n5 3\n\n0 0 1 0 0", "output": ["YES\nYES\nYES\nNO\nYES\nYES\nYES"]}]
|
block_completion_006995
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can: Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.
Input Specification: The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) β the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).
Output Specification: For each test case, print one integer β the minimum number of days required to water the trees, so they grow to the same height.
Notes: NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$. During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$; during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.
Code:
def solve(m,a):
ev=od=0
for i in a:
ev += (m-i)//2; od += (m-i)%2
if(od>=ev):
# TODO: Your code here
ev = (ev-od)*2
return od*2 + ev//3*2 + ev%3
I = lambda: map(int,input().split())
t,=I()
for _ in [1]*t:
n, = I()
b = [*I()]
mx = max(b)
print(min(solve(mx,b),solve(mx+1,b)))
|
def solve(m,a):
ev=od=0
for i in a:
ev += (m-i)//2; od += (m-i)%2
if(od>=ev):
{{completion}}
ev = (ev-od)*2
return od*2 + ev//3*2 + ev%3
I = lambda: map(int,input().split())
t,=I()
for _ in [1]*t:
n, = I()
b = [*I()]
mx = max(b)
print(min(solve(mx,b),solve(mx+1,b)))
|
return od*2-(od!=ev)
|
[{"input": "3\n3\n1 2 4\n5\n4 4 3 5 5\n7\n2 5 4 8 3 7 4", "output": ["4\n3\n16"]}]
|
block_completion_003422
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
Input Specification: The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ Β β the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ Β β the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
Code:
input = __import__('sys').stdin.readline
def solve():
n = int(input())
allzeros = False
total = 0
for x in map(int, input().split()):
total += x
if # TODO: Your code here:
print('No')
return
allzeros = allzeros or total == 0
print('YES' if total == 0 else 'NO')
for _ in range(int(input())):
solve()
|
input = __import__('sys').stdin.readline
def solve():
n = int(input())
allzeros = False
total = 0
for x in map(int, input().split()):
total += x
if {{completion}}:
print('No')
return
allzeros = allzeros or total == 0
print('YES' if total == 0 else 'NO')
for _ in range(int(input())):
solve()
|
total < 0 or total != 0 and allzeros
|
[{"input": "7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0", "output": ["No\nYes\nNo\nNo\nYes\nYes\nYes"]}]
|
control_completion_000426
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \leq i \leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \leq i \leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)?
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) β the elements of the array $$$a$$$.
Output Specification: Print a single integer, the minimum number of moves to make $$$b$$$ increasing.
Notes: NoteExample $$$1$$$: you can subtract $$$a_1$$$ from $$$b_1$$$, and add $$$a_3$$$, $$$a_4$$$, and $$$a_5$$$ to $$$b_3$$$, $$$b_4$$$, and $$$b_5$$$ respectively. The final array will be [$$$-1$$$, $$$0$$$, $$$3$$$, $$$4$$$, $$$5$$$] after $$$4$$$ moves.Example $$$2$$$: you can reach [$$$-3$$$, $$$-2$$$, $$$-1$$$, $$$0$$$, $$$1$$$, $$$2$$$, $$$3$$$] in $$$10$$$ moves.
Code:
n=int(input())
a=list(map(int,input().split()))
b=[int(0) for _ in range(n)]
m=1e18
for i in range(n):
c=0
p=0
for # TODO: Your code here:
p+=a[j]-p%a[j]
c+=p//a[j]
p=0
for j in range(i-1,-1,-1):
p+=a[j]-p%a[j]
c+=p//a[j]
m=min(m,c)
print(m)
|
n=int(input())
a=list(map(int,input().split()))
b=[int(0) for _ in range(n)]
m=1e18
for i in range(n):
c=0
p=0
for {{completion}}:
p+=a[j]-p%a[j]
c+=p//a[j]
p=0
for j in range(i-1,-1,-1):
p+=a[j]-p%a[j]
c+=p//a[j]
m=min(m,c)
print(m)
|
j in range(i+1,len(b))
|
[{"input": "5\n1 2 3 4 5", "output": ["4"]}, {"input": "7\n1 2 1 2 1 2 1", "output": ["10"]}, {"input": "8\n1 8 2 7 3 6 4 5", "output": ["16"]}]
|
control_completion_000970
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) β indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 10^5$$$)Β β number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) β the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) β indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
from collections import deque;import math
import sys;I=sys.stdin.readline;R=lambda:map(lambda x:int(x)-1,input().split())
n=int(I());g=[[] for _ in range(n)]
for _ in [0]*(n-1):
u,v=R();g[u].append(v);g[v].append(u)
h=math.ceil(math.log2(n))
fa=[[-1]*(h+1) for _ in range(n)];dep=[0]*n
q=deque([0])
while q:
u=q.popleft()
for v in g[u]:
if # TODO: Your code here:fa[v][0]=u;dep[v]=dep[u]+1;q.append(v)
for i in range(1,h+1):
for u in range(n):
fa[u][i]=fa[fa[u][i-1]][i-1]
def lca(u,v):
if dep[u]<dep[v]:u,v=v,u
for i in range(h,-1,-1):
if dep[v]+(1<<i)<=dep[u]:u=fa[u][i]
if u==v:return u
for i in range(h,-1,-1):
if fa[u][i]!=fa[v][i]:u=fa[u][i];v=fa[v][i]
return fa[u][0]
for _ in [0]*int(I()):
k=int(I());p=[*R()];z='YES'
if k<=2:print(z);continue
p.sort(key=lambda u:dep[u])
u=p.pop();v=p.pop();f=lca(u,v)
while p and f==v:u=v;v=p.pop();f=lca(u,v)
for x in p:
if dep[x]<=dep[f] and x!=f or lca(u,x)!=x and lca(v,x)!=x:
z='NO';break
print(z)
|
from collections import deque;import math
import sys;I=sys.stdin.readline;R=lambda:map(lambda x:int(x)-1,input().split())
n=int(I());g=[[] for _ in range(n)]
for _ in [0]*(n-1):
u,v=R();g[u].append(v);g[v].append(u)
h=math.ceil(math.log2(n))
fa=[[-1]*(h+1) for _ in range(n)];dep=[0]*n
q=deque([0])
while q:
u=q.popleft()
for v in g[u]:
if {{completion}}:fa[v][0]=u;dep[v]=dep[u]+1;q.append(v)
for i in range(1,h+1):
for u in range(n):
fa[u][i]=fa[fa[u][i-1]][i-1]
def lca(u,v):
if dep[u]<dep[v]:u,v=v,u
for i in range(h,-1,-1):
if dep[v]+(1<<i)<=dep[u]:u=fa[u][i]
if u==v:return u
for i in range(h,-1,-1):
if fa[u][i]!=fa[v][i]:u=fa[u][i];v=fa[v][i]
return fa[u][0]
for _ in [0]*int(I()):
k=int(I());p=[*R()];z='YES'
if k<=2:print(z);continue
p.sort(key=lambda u:dep[u])
u=p.pop();v=p.pop();f=lca(u,v)
while p and f==v:u=v;v=p.pop();f=lca(u,v)
for x in p:
if dep[x]<=dep[f] and x!=f or lca(u,x)!=x and lca(v,x)!=x:
z='NO';break
print(z)
|
v!=fa[u][0]
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
control_completion_002241
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that $$$a + b + c + d = n$$$, and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $$$n$$$ ($$$4 \le n \le 10^9$$$)Β β the sum of $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$.
Output Specification: For each test case output $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ such that $$$a + b + c + d = n$$$ and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.
Notes: NoteIn the first test case $$$\gcd(1, 1) = \operatorname{lcm}(1, 1) = 1$$$, $$$1 + 1 + 1 + 1 = 4$$$.In the second test case $$$\gcd(2, 2) = \operatorname{lcm}(2, 1) = 2$$$, $$$2 + 2 + 2 + 1 = 7$$$.In the third test case $$$\gcd(2, 2) = \operatorname{lcm}(2, 2) = 2$$$, $$$2 + 2 + 2 + 2 = 8$$$.In the fourth test case $$$\gcd(2, 4) = \operatorname{lcm}(2, 1) = 2$$$, $$$2 + 4 + 2 + 1 = 9$$$.In the fifth test case $$$\gcd(3, 5) = \operatorname{lcm}(1, 1) = 1$$$, $$$3 + 5 + 1 + 1 = 10$$$.
Code:
for _ in range(int(input())):
a=int(input())
if a%4==0:
print(a//4,a//4,a//4,a//4)
else:
if a%2==1:
a1=(a-1)
if a1%3==0:
print(a1//3,a1//3,a1//3,1)
elif a1%4!=0:
# TODO: Your code here
elif a1%4==0:
print(a1//4,a1//2,a1//4,1)
else:
a1=a-2
print(a1//2-1,a1//2+1,1,1)
|
for _ in range(int(input())):
a=int(input())
if a%4==0:
print(a//4,a//4,a//4,a//4)
else:
if a%2==1:
a1=(a-1)
if a1%3==0:
print(a1//3,a1//3,a1//3,1)
elif a1%4!=0:
{{completion}}
elif a1%4==0:
print(a1//4,a1//2,a1//4,1)
else:
a1=a-2
print(a1//2-1,a1//2+1,1,1)
|
a1=a-2
print(a1//2,a1//2+1,1,1)
|
[{"input": "5\n4\n7\n8\n9\n10", "output": ["1 1 1 1\n2 2 2 1\n2 2 2 2\n2 4 2 1\n3 5 1 1"]}]
|
block_completion_004461
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for sdr in[*open(0)][2::2]:# TODO: Your code here
|
for sdr in[*open(0)][2::2]:{{completion}}
|
p,q,*_,r,s=sorted(map(int,sdr.split()));print(r+s-p-q)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005387
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
n, q = list(map(int, input().split()))
a = list(map(int, input().split()))
x, c, s, b = 0, 0, sum(a), [1]*(n)
for i in range(q):
k = list(map(int, input().split()))
if k[0]==1:
j = k[1]-1
if # TODO: Your code here:
s = s-a[j]+k[2]
else:
s = s-x+k[2]
b[j] = c+1
a[j] = k[2]
print(s)
else:
c = c+1
x = k[1]
s = n*x
print(s)
|
n, q = list(map(int, input().split()))
a = list(map(int, input().split()))
x, c, s, b = 0, 0, sum(a), [1]*(n)
for i in range(q):
k = list(map(int, input().split()))
if k[0]==1:
j = k[1]-1
if {{completion}}:
s = s-a[j]+k[2]
else:
s = s-x+k[2]
b[j] = c+1
a[j] = k[2]
print(s)
else:
c = c+1
x = k[1]
s = n*x
print(s)
|
b[j]>c
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
control_completion_005516
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$Β β the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$)Β β the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.
Output Specification: For each query, print a single integerΒ β the maximum total value of items received for free for one purchase.
Notes: NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.
Code:
import sys
n, p = map(int, sys.stdin.readline().split())
l = map(int, sys.stdin.readline().split())
l = sorted(l, reverse=True)
for i in range(n-1, 0, -1):
l[i-1] += l[i]
for _ in range(p):
xi, yi = map(int, sys.stdin.readline().split())
a = n-xi
b = a+yi
if a == 0:
print(l[-b])
else:
# TODO: Your code here
|
import sys
n, p = map(int, sys.stdin.readline().split())
l = map(int, sys.stdin.readline().split())
l = sorted(l, reverse=True)
for i in range(n-1, 0, -1):
l[i-1] += l[i]
for _ in range(p):
xi, yi = map(int, sys.stdin.readline().split())
a = n-xi
b = a+yi
if a == 0:
print(l[-b])
else:
{{completion}}
|
print(l[-b]-l[-a])
|
[{"input": "5 3\n5 3 1 5 2\n3 2\n1 1\n5 3", "output": ["8\n5\n6"]}]
|
block_completion_000520
|
block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.