lang
stringclasses 1
value | prompt
stringlengths 1.38k
11.3k
| eval_prompt
stringlengths 37
8.09k
| ground_truth
stringlengths 1
328
| unit_tests
stringclasses 145
values | task_id
stringlengths 23
25
| split
stringclasses 2
values |
|---|---|---|---|---|---|---|
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:
d = int(input().split(" ")[1])
p = sorted(map(int, input().split(" ")))
c = 0
l = 0
r = len(p) - 1
s = p[r]
while r > l:
while s <= d:
s += p[r]
l += 1
if l > r:
# TODO: Your code here
r -= 1
s = p[r]
c += 1
if p[0] > d:
c += 1
print(c)
|
d = int(input().split(" ")[1])
p = sorted(map(int, input().split(" ")))
c = 0
l = 0
r = len(p) - 1
s = p[r]
while r > l:
while s <= d:
s += p[r]
l += 1
if l > r:
{{completion}}
r -= 1
s = p[r]
c += 1
if p[0] > d:
c += 1
print(c)
|
break
|
[{"input": "6 180\n90 80 70 60 50 100", "output": ["2"]}]
|
block_completion_003730
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $$$N$$$ vertices and $$$M$$$ edges. In the graph, edge $$$i$$$ connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. By using the $$$i$$$-th edge, something can move from $$$U_i$$$ to $$$V_i$$$, but not from $$$V_i$$$ to $$$U_i$$$.To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $$$U_i$$$ to vertex $$$V_i$$$, Pak Chanek needs a time of $$$W_i$$$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.Pak Chanek has several questions. For each $$$p$$$ satisfying $$$2 \leq p \leq N$$$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$p$$$, or report if it is impossible.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$2 \leq N \leq 10^5$$$, $$$0 \leq M \leq 2 \cdot 10^5$$$) β the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$M$$$ lines contains three integers $$$U_i$$$, $$$V_i$$$, and $$$W_i$$$ ($$$1 \le U_i, V_i \le N$$$, $$$U_i \neq V_i$$$, $$$1 \le W_i \le 10^9$$$) β a directed edge that connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. There is no pair of different edges $$$i$$$ and $$$j$$$ such that $$$U_i = U_j$$$ and $$$V_i = V_j$$$.
Output Specification: Output a line containing $$$N-1$$$ integers. The $$$j$$$-th integer represents the minimum time in seconds needed by Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$j+1$$$, or $$$-1$$$ if it is impossible.
Notes: NoteIf initially Pak Chanek's left hand is on vertex $$$1$$$ and his right hand is on vertex $$$5$$$, Pak Chanek can do the following moves: Move his right hand to vertex $$$4$$$ in $$$1$$$ second. Move his left hand to vertex $$$2$$$ in $$$2$$$ seconds. Move his left hand to vertex $$$4$$$ in $$$1$$$ second. In total it needs $$$1+2+1=4$$$ seconds. It can be proven that there is no other way that is faster.
Code:
import sys
input=sys.stdin.readline
from heapq import heappush,heappop,heapify
from collections import defaultdict
def main():
n,m=map(int,input().split())
gf=defaultdict(list)
gb=defaultdict(list)
for _ in range(m):
u,v,w=map(int,input().split())
gf[u].append((v,w))
gb[v].append((u,w))
dis=[float('inf')]*(n+1)
dis[1]=0
h=[]
heapify(h)
heappush(h,(0,1))
while h:
cd,cn=heappop(h)
if dis[cn]==cd:
for nn,nw in gf[cn]:
if cd+nw<dis[nn]:
# TODO: Your code here
res=[float('inf')]*(n+1)
res[1]=0
h=[]
for i in range(1,n+1):
if dis[i]!=float('inf'):
res[i]=dis[i]
h.append((dis[i],i))
heapify(h)
while h:
cd,cn=heappop(h)
if res[cn]==cd:
for nn,nw in gb[cn]:
if cd+nw<res[nn]:
res[nn]=cd+nw
heappush(h,(nw+cd,nn))
for i in range(1,len(res)):
if res[i]==float('inf'):res[i]=-1
print(*res[2:])
main()
|
import sys
input=sys.stdin.readline
from heapq import heappush,heappop,heapify
from collections import defaultdict
def main():
n,m=map(int,input().split())
gf=defaultdict(list)
gb=defaultdict(list)
for _ in range(m):
u,v,w=map(int,input().split())
gf[u].append((v,w))
gb[v].append((u,w))
dis=[float('inf')]*(n+1)
dis[1]=0
h=[]
heapify(h)
heappush(h,(0,1))
while h:
cd,cn=heappop(h)
if dis[cn]==cd:
for nn,nw in gf[cn]:
if cd+nw<dis[nn]:
{{completion}}
res=[float('inf')]*(n+1)
res[1]=0
h=[]
for i in range(1,n+1):
if dis[i]!=float('inf'):
res[i]=dis[i]
h.append((dis[i],i))
heapify(h)
while h:
cd,cn=heappop(h)
if res[cn]==cd:
for nn,nw in gb[cn]:
if cd+nw<res[nn]:
res[nn]=cd+nw
heappush(h,(nw+cd,nn))
for i in range(1,len(res)):
if res[i]==float('inf'):res[i]=-1
print(*res[2:])
main()
|
dis[nn]=cd+nw
heappush(h,(nw+cd,nn))
|
[{"input": "5 7\n1 2 2\n2 4 1\n4 1 4\n2 5 3\n5 4 1\n5 2 4\n2 1 1", "output": ["1 -1 3 4"]}]
|
block_completion_003746
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $$$N$$$ vertices and $$$M$$$ edges. In the graph, edge $$$i$$$ connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. By using the $$$i$$$-th edge, something can move from $$$U_i$$$ to $$$V_i$$$, but not from $$$V_i$$$ to $$$U_i$$$.To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $$$U_i$$$ to vertex $$$V_i$$$, Pak Chanek needs a time of $$$W_i$$$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.Pak Chanek has several questions. For each $$$p$$$ satisfying $$$2 \leq p \leq N$$$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$p$$$, or report if it is impossible.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$2 \leq N \leq 10^5$$$, $$$0 \leq M \leq 2 \cdot 10^5$$$) β the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$M$$$ lines contains three integers $$$U_i$$$, $$$V_i$$$, and $$$W_i$$$ ($$$1 \le U_i, V_i \le N$$$, $$$U_i \neq V_i$$$, $$$1 \le W_i \le 10^9$$$) β a directed edge that connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. There is no pair of different edges $$$i$$$ and $$$j$$$ such that $$$U_i = U_j$$$ and $$$V_i = V_j$$$.
Output Specification: Output a line containing $$$N-1$$$ integers. The $$$j$$$-th integer represents the minimum time in seconds needed by Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$j+1$$$, or $$$-1$$$ if it is impossible.
Notes: NoteIf initially Pak Chanek's left hand is on vertex $$$1$$$ and his right hand is on vertex $$$5$$$, Pak Chanek can do the following moves: Move his right hand to vertex $$$4$$$ in $$$1$$$ second. Move his left hand to vertex $$$2$$$ in $$$2$$$ seconds. Move his left hand to vertex $$$4$$$ in $$$1$$$ second. In total it needs $$$1+2+1=4$$$ seconds. It can be proven that there is no other way that is faster.
Code:
import sys
input=sys.stdin.readline
from heapq import heappush,heappop,heapify
from collections import defaultdict
def main():
n,m=map(int,input().split())
gf=defaultdict(list)
gb=defaultdict(list)
for _ in range(m):
u,v,w=map(int,input().split())
gf[u].append((v,w))
gb[v].append((u,w))
dis=[float('inf')]*(n+1)
dis[1]=0
h=[]
heapify(h)
heappush(h,(0,1))
while h:
cd,cn=heappop(h)
if dis[cn]==cd:
for nn,nw in gf[cn]:
if cd+nw<dis[nn]:
dis[nn]=cd+nw
heappush(h,(nw+cd,nn))
res=[float('inf')]*(n+1)
res[1]=0
h=[]
for i in range(1,n+1):
if dis[i]!=float('inf'):
res[i]=dis[i]
h.append((dis[i],i))
heapify(h)
while h:
cd,cn=heappop(h)
if res[cn]==cd:
for nn,nw in gb[cn]:
if cd+nw<res[nn]:
# TODO: Your code here
for i in range(1,len(res)):
if res[i]==float('inf'):res[i]=-1
print(*res[2:])
main()
|
import sys
input=sys.stdin.readline
from heapq import heappush,heappop,heapify
from collections import defaultdict
def main():
n,m=map(int,input().split())
gf=defaultdict(list)
gb=defaultdict(list)
for _ in range(m):
u,v,w=map(int,input().split())
gf[u].append((v,w))
gb[v].append((u,w))
dis=[float('inf')]*(n+1)
dis[1]=0
h=[]
heapify(h)
heappush(h,(0,1))
while h:
cd,cn=heappop(h)
if dis[cn]==cd:
for nn,nw in gf[cn]:
if cd+nw<dis[nn]:
dis[nn]=cd+nw
heappush(h,(nw+cd,nn))
res=[float('inf')]*(n+1)
res[1]=0
h=[]
for i in range(1,n+1):
if dis[i]!=float('inf'):
res[i]=dis[i]
h.append((dis[i],i))
heapify(h)
while h:
cd,cn=heappop(h)
if res[cn]==cd:
for nn,nw in gb[cn]:
if cd+nw<res[nn]:
{{completion}}
for i in range(1,len(res)):
if res[i]==float('inf'):res[i]=-1
print(*res[2:])
main()
|
res[nn]=cd+nw
heappush(h,(nw+cd,nn))
|
[{"input": "5 7\n1 2 2\n2 4 1\n4 1 4\n2 5 3\n5 4 1\n5 2 4\n2 1 1", "output": ["1 -1 3 4"]}]
|
block_completion_003747
|
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,s,sum = 1,1,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)
mul,ded,turn = 0,0,0
t -= 0 if mx==turn else 1
for i in range(q):
x = int(input())
if x == 1:
print(1)
continue
while True:
if x-ded <= t:
# TODO: Your code here
ded += (t+1)//2
turn+=1
mul += 1
t -= 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,s,sum = 1,1,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)
mul,ded,turn = 0,0,0
t -= 0 if mx==turn else 1
for i in range(q):
x = int(input())
if x == 1:
print(1)
continue
while True:
if x-ded <= t:
{{completion}}
ded += (t+1)//2
turn+=1
mul += 1
t -= 0 if mx==turn else 1
|
print(ev(x-ded)+mul)
break
|
[{"input": "6 3\n1\n4\n5", "output": ["17\n1\n3\n4"]}, {"input": "1 0", "output": ["1"]}]
|
block_completion_003753
|
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 x-ded <= tt:
# TODO: Your code here
#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 x-ded <= tt:
{{completion}}
#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
|
print(ev(x-ded)+mul)
break
|
[{"input": "6 3\n1\n4\n5", "output": ["17\n1\n3\n4"]}, {"input": "1 0", "output": ["1"]}]
|
block_completion_003754
|
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 x-ded <= tt:
print(ev(x-ded)+mul)
break
#print("WUT")
if tt < 0:
# TODO: Your code here
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 x-ded <= tt:
print(ev(x-ded)+mul)
break
#print("WUT")
if tt < 0:
{{completion}}
ded += (tt+1)//2
turn+=1
mul += 1
tt -= 0 if mx==turn else 1
|
print(ev(x-ded)+mul)
break
|
[{"input": "6 3\n1\n4\n5", "output": ["17\n1\n3\n4"]}, {"input": "1 0", "output": ["1"]}]
|
block_completion_003755
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has a mirror in the shape of a circle. There are $$$N$$$ lamps on the circumference numbered from $$$1$$$ to $$$N$$$ in clockwise order. The length of the arc from lamp $$$i$$$ to lamp $$$i+1$$$ is $$$D_i$$$ for $$$1 \leq i \leq N-1$$$. Meanwhile, the length of the arc between lamp $$$N$$$ and lamp $$$1$$$ is $$$D_N$$$.Pak Chanek wants to colour the lamps with $$$M$$$ different colours. Each lamp can be coloured with one of the $$$M$$$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $$$90$$$ degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps $$$1$$$, $$$2$$$, and $$$3$$$ form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \le N \le 3 \cdot 10^5$$$, $$$2 \le M \le 3 \cdot 10^5$$$) β the number of lamps in the mirror and the number of different colours used. The second line contains $$$N$$$ integers $$$D_1, D_2, \ldots, D_N$$$ ($$$1 \le D_i \le 10^9$$$) β the lengths of the arcs between the lamps in the mirror.
Output Specification: An integer representing the number of possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, all correct lamp colouring configurations are $$$[1, 1, 2, 1]$$$, $$$[1, 1, 2, 2]$$$, $$$[1, 2, 1, 2]$$$, $$$[1, 2, 2, 1]$$$, $$$[1, 2, 2, 2]$$$, $$$[2, 1, 1, 1]$$$, $$$[2, 1, 1, 2]$$$, $$$[2, 1, 2, 1]$$$, $$$[2, 2, 1, 1]$$$, and $$$[2, 2, 1, 2]$$$.
Code:
import sys
#sys.stdin = open("C:\\Users\\asawe\\Documents\\input.txt","r")
mx = 3 * (10 ** 5) + 10
mod = 998244353
fact = [1]
inv_fact = [1]
def modpow(a, b, m):
res = 1
x = a
y = b
while (y > 0):
if (y & 1):
# TODO: Your code here
y = y >> 1
x = ((x % m) * (x % m)) % m
return (res % m + m) % m
def inverse(a, m):
u,v = 0,1
while a != 0:
t = m // a
m -= t * a
a, m = m, a
u -= t * v
u, v = v, u
return u
for i in range(1, mx):
fact.append((fact[-1] * i) % mod)
inv_fact.append(inverse(fact[-1], mod)%mod)
def P(n, k):
if k < 0 or k > n:
return 0
return (fact[n] * inv_fact[n - k]) % mod
def C(n, k):
if k < 0 or k > n:
return 0
return (fact[n] * inv_fact[k] * inv_fact[n - k]) % mod
n,m = map(int,sys.stdin.readline().split())
a = list(map(int,sys.stdin.readline().split()))
s = sum(a)
psum = [0] * n
for i in range(n-1):
psum[i] = psum[i-1] + a[i]
di = {}
for i in psum:
di[i] = 0
count = 0
for i in psum:
if i + s/2 in di:
count+=1
v = n - 2 * count
ans = 0
for i in range(count+1):
ans = (ans + C(count,i) * P(m,count-i) * modpow(m-count+i,v,mod) * modpow(P(m-count+i,2),i,mod)) % mod
print(ans)
|
import sys
#sys.stdin = open("C:\\Users\\asawe\\Documents\\input.txt","r")
mx = 3 * (10 ** 5) + 10
mod = 998244353
fact = [1]
inv_fact = [1]
def modpow(a, b, m):
res = 1
x = a
y = b
while (y > 0):
if (y & 1):
{{completion}}
y = y >> 1
x = ((x % m) * (x % m)) % m
return (res % m + m) % m
def inverse(a, m):
u,v = 0,1
while a != 0:
t = m // a
m -= t * a
a, m = m, a
u -= t * v
u, v = v, u
return u
for i in range(1, mx):
fact.append((fact[-1] * i) % mod)
inv_fact.append(inverse(fact[-1], mod)%mod)
def P(n, k):
if k < 0 or k > n:
return 0
return (fact[n] * inv_fact[n - k]) % mod
def C(n, k):
if k < 0 or k > n:
return 0
return (fact[n] * inv_fact[k] * inv_fact[n - k]) % mod
n,m = map(int,sys.stdin.readline().split())
a = list(map(int,sys.stdin.readline().split()))
s = sum(a)
psum = [0] * n
for i in range(n-1):
psum[i] = psum[i-1] + a[i]
di = {}
for i in psum:
di[i] = 0
count = 0
for i in psum:
if i + s/2 in di:
count+=1
v = n - 2 * count
ans = 0
for i in range(count+1):
ans = (ans + C(count,i) * P(m,count-i) * modpow(m-count+i,v,mod) * modpow(P(m-count+i,2),i,mod)) % mod
print(ans)
|
res = (res * x) % m
|
[{"input": "4 2\n10 10 6 14", "output": ["10"]}, {"input": "1 2\n10", "output": ["2"]}]
|
block_completion_003765
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has a mirror in the shape of a circle. There are $$$N$$$ lamps on the circumference numbered from $$$1$$$ to $$$N$$$ in clockwise order. The length of the arc from lamp $$$i$$$ to lamp $$$i+1$$$ is $$$D_i$$$ for $$$1 \leq i \leq N-1$$$. Meanwhile, the length of the arc between lamp $$$N$$$ and lamp $$$1$$$ is $$$D_N$$$.Pak Chanek wants to colour the lamps with $$$M$$$ different colours. Each lamp can be coloured with one of the $$$M$$$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $$$90$$$ degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps $$$1$$$, $$$2$$$, and $$$3$$$ form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \le N \le 3 \cdot 10^5$$$, $$$2 \le M \le 3 \cdot 10^5$$$) β the number of lamps in the mirror and the number of different colours used. The second line contains $$$N$$$ integers $$$D_1, D_2, \ldots, D_N$$$ ($$$1 \le D_i \le 10^9$$$) β the lengths of the arcs between the lamps in the mirror.
Output Specification: An integer representing the number of possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, all correct lamp colouring configurations are $$$[1, 1, 2, 1]$$$, $$$[1, 1, 2, 2]$$$, $$$[1, 2, 1, 2]$$$, $$$[1, 2, 2, 1]$$$, $$$[1, 2, 2, 2]$$$, $$$[2, 1, 1, 1]$$$, $$$[2, 1, 1, 2]$$$, $$$[2, 1, 2, 1]$$$, $$$[2, 2, 1, 1]$$$, and $$$[2, 2, 1, 2]$$$.
Code:
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
res = (res*a)%p
n-=1
else:
# TODO: Your code here
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
anss+=ans
print(anss%pmod)
|
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
res = (res*a)%p
n-=1
else:
{{completion}}
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
anss+=ans
print(anss%pmod)
|
a = (a*a)%p
n//=2
|
[{"input": "4 2\n10 10 6 14", "output": ["10"]}, {"input": "1 2\n10", "output": ["2"]}]
|
block_completion_003766
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has a mirror in the shape of a circle. There are $$$N$$$ lamps on the circumference numbered from $$$1$$$ to $$$N$$$ in clockwise order. The length of the arc from lamp $$$i$$$ to lamp $$$i+1$$$ is $$$D_i$$$ for $$$1 \leq i \leq N-1$$$. Meanwhile, the length of the arc between lamp $$$N$$$ and lamp $$$1$$$ is $$$D_N$$$.Pak Chanek wants to colour the lamps with $$$M$$$ different colours. Each lamp can be coloured with one of the $$$M$$$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $$$90$$$ degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps $$$1$$$, $$$2$$$, and $$$3$$$ form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \le N \le 3 \cdot 10^5$$$, $$$2 \le M \le 3 \cdot 10^5$$$) β the number of lamps in the mirror and the number of different colours used. The second line contains $$$N$$$ integers $$$D_1, D_2, \ldots, D_N$$$ ($$$1 \le D_i \le 10^9$$$) β the lengths of the arcs between the lamps in the mirror.
Output Specification: An integer representing the number of possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, all correct lamp colouring configurations are $$$[1, 1, 2, 1]$$$, $$$[1, 1, 2, 2]$$$, $$$[1, 2, 1, 2]$$$, $$$[1, 2, 2, 1]$$$, $$$[1, 2, 2, 2]$$$, $$$[2, 1, 1, 1]$$$, $$$[2, 1, 1, 2]$$$, $$$[2, 1, 2, 1]$$$, $$$[2, 2, 1, 1]$$$, and $$$[2, 2, 1, 2]$$$.
Code:
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
# TODO: Your code here
else:
a = (a*a)%p
n//=2
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
anss+=ans
print(anss%pmod)
|
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
{{completion}}
else:
a = (a*a)%p
n//=2
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
anss+=ans
print(anss%pmod)
|
res = (res*a)%p
n-=1
|
[{"input": "4 2\n10 10 6 14", "output": ["10"]}, {"input": "1 2\n10", "output": ["2"]}]
|
block_completion_003767
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has a mirror in the shape of a circle. There are $$$N$$$ lamps on the circumference numbered from $$$1$$$ to $$$N$$$ in clockwise order. The length of the arc from lamp $$$i$$$ to lamp $$$i+1$$$ is $$$D_i$$$ for $$$1 \leq i \leq N-1$$$. Meanwhile, the length of the arc between lamp $$$N$$$ and lamp $$$1$$$ is $$$D_N$$$.Pak Chanek wants to colour the lamps with $$$M$$$ different colours. Each lamp can be coloured with one of the $$$M$$$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $$$90$$$ degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps $$$1$$$, $$$2$$$, and $$$3$$$ form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \le N \le 3 \cdot 10^5$$$, $$$2 \le M \le 3 \cdot 10^5$$$) β the number of lamps in the mirror and the number of different colours used. The second line contains $$$N$$$ integers $$$D_1, D_2, \ldots, D_N$$$ ($$$1 \le D_i \le 10^9$$$) β the lengths of the arcs between the lamps in the mirror.
Output Specification: An integer representing the number of possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, all correct lamp colouring configurations are $$$[1, 1, 2, 1]$$$, $$$[1, 1, 2, 2]$$$, $$$[1, 2, 1, 2]$$$, $$$[1, 2, 2, 1]$$$, $$$[1, 2, 2, 2]$$$, $$$[2, 1, 1, 1]$$$, $$$[2, 1, 1, 2]$$$, $$$[2, 1, 2, 1]$$$, $$$[2, 2, 1, 1]$$$, and $$$[2, 2, 1, 2]$$$.
Code:
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
res = (res*a)%p
n-=1
else:
# TODO: Your code here
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
ans%=pmod
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
ans%=pmod
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
ans%=pmod
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
ans%=pmod
anss+=ans
print(anss%pmod)
|
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
res = (res*a)%p
n-=1
else:
{{completion}}
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
ans%=pmod
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
ans%=pmod
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
ans%=pmod
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
ans%=pmod
anss+=ans
print(anss%pmod)
|
a = (a*a)%p
n//=2
|
[{"input": "4 2\n10 10 6 14", "output": ["10"]}, {"input": "1 2\n10", "output": ["2"]}]
|
block_completion_003768
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has a mirror in the shape of a circle. There are $$$N$$$ lamps on the circumference numbered from $$$1$$$ to $$$N$$$ in clockwise order. The length of the arc from lamp $$$i$$$ to lamp $$$i+1$$$ is $$$D_i$$$ for $$$1 \leq i \leq N-1$$$. Meanwhile, the length of the arc between lamp $$$N$$$ and lamp $$$1$$$ is $$$D_N$$$.Pak Chanek wants to colour the lamps with $$$M$$$ different colours. Each lamp can be coloured with one of the $$$M$$$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $$$90$$$ degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps $$$1$$$, $$$2$$$, and $$$3$$$ form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Input Specification: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \le N \le 3 \cdot 10^5$$$, $$$2 \le M \le 3 \cdot 10^5$$$) β the number of lamps in the mirror and the number of different colours used. The second line contains $$$N$$$ integers $$$D_1, D_2, \ldots, D_N$$$ ($$$1 \le D_i \le 10^9$$$) β the lengths of the arcs between the lamps in the mirror.
Output Specification: An integer representing the number of possible lamp colouring configurations, modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, all correct lamp colouring configurations are $$$[1, 1, 2, 1]$$$, $$$[1, 1, 2, 2]$$$, $$$[1, 2, 1, 2]$$$, $$$[1, 2, 2, 1]$$$, $$$[1, 2, 2, 2]$$$, $$$[2, 1, 1, 1]$$$, $$$[2, 1, 1, 2]$$$, $$$[2, 1, 2, 1]$$$, $$$[2, 2, 1, 1]$$$, and $$$[2, 2, 1, 2]$$$.
Code:
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
# TODO: Your code here
else:
a = (a*a)%p
n//=2
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
ans%=pmod
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
ans%=pmod
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
ans%=pmod
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
ans%=pmod
anss+=ans
print(anss%pmod)
|
from math import comb
def bpow(a,n,p):
res = 1
while n:
if n%2:
{{completion}}
else:
a = (a*a)%p
n//=2
return res
N = 3 * 10**5 + 5
factorialNumInverse = [None] * (N + 1)
naturalNumInverse = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def Binomial(N, R, p):
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
pmod = 998244353
InverseofNumber(pmod)
InverseofFactorial(pmod)
factorial(pmod)
n,pp = map(int,input().split())
l = list(map(int,input().split()))
pref,a = 0,[]
for i in l:
pref+=i
a.append(pref)
qq = pref
qq = qq/2
q = 1
k = 0
po = 0
p = 0
while(q<n):
if(a[q]-a[po]>qq):
po+=1
elif(a[q]-a[po]<qq):
q+=1
else:
k+=1
po+=1
q+=1
p=pp
anss = 0
for i in range(k+1):
ans=1
ans*=Binomial(k,k-i,pmod)
ans%=pmod
#print(f'ans after step 1 is {ans}')
ans*=bpow(((p-(k-i))*(p-(k-i)-1)),i,pmod)
ans%=pmod
#print(f'ans after step 2 is {ans}')
ans*=fact[p]*factorialNumInverse[p-k+i]
ans%=pmod
#print(f'ans after step 3 is {ans}')
ans*=bpow(p-k+i,(n-k*2),pmod)
ans%=pmod
anss+=ans
print(anss%pmod)
|
res = (res*a)%p
n-=1
|
[{"input": "4 2\n10 10 6 14", "output": ["10"]}, {"input": "1 2\n10", "output": ["2"]}]
|
block_completion_003769
|
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: 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:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
# TODO: Your code here
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:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
{{completion}}
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)
|
stop -= 1
res_right = self._func(self.data[stop], res_right)
|
[{"input": "7\n2 -1 -1 5 2 -2 9", "output": ["4"]}, {"input": "5\n-1 -2 -3 -4 -5", "output": ["-1"]}]
|
block_completion_003792
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Kristina has two arrays $$$a$$$ and $$$b$$$, each containing $$$n$$$ non-negative integers. She can perform the following operation on array $$$a$$$ any number of times: apply a decrement to each non-zero element of the array, that is, replace the value of each element $$$a_i$$$ such that $$$a_i > 0$$$ with the value $$$a_i - 1$$$ ($$$1 \le i \le n$$$). If $$$a_i$$$ was $$$0$$$, its value does not change. Determine whether Kristina can get an array $$$b$$$ from an array $$$a$$$ in some number of operations (probably zero). In other words, can she make $$$a_i = b_i$$$ after some number of operations for each $$$1 \le i \le n$$$?For example, let $$$n = 4$$$, $$$a = [3, 5, 4, 1]$$$ and $$$b = [1, 3, 2, 0]$$$. In this case, she can apply the operation twice: after the first application of the operation she gets $$$a = [2, 4, 3, 0]$$$; after the second use of the operation she gets $$$a = [1, 3, 2, 0]$$$. Thus, in two operations, she can get an array $$$b$$$ from an array $$$a$$$.
Input Specification: The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β βthe number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$). The second line of each test case contains exactly $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ non-negative integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output on a separate line: YES, if by doing some number of operations it is possible to get an array $$$b$$$ from an array $$$a$$$; NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
Notes: NoteThe first test case is analyzed in the statement.In the second test case, it is enough to apply the operation to array $$$a$$$ once.In the third test case, it is impossible to get array $$$b$$$ from array $$$a$$$.
Code:
def solve(a, b):
inf = 2 * 10 ** 6
d, n = inf, len(b)
for i in range(n):
if b[i] > 0:
# TODO: Your code here
# b[i] > a[i]
if d < 0:
print("NO")
return
# All elements of b are 0s
if d == inf:
print("YES")
return
for i in range(n):
if a[i] - b[i] > d:
print("NO")
return
if b[i] > 0 and a[i] - b[i] < d:
print("NO")
return
# all a[i] - b[i] == d
print("YES")
def main():
from sys import stdin
from itertools import islice
tkns = map(int, stdin.read().split())
t = next(tkns)
for T in range(t):
n = next(tkns)
a, b = list(islice(tkns, n)), list(islice(tkns, n))
solve(a, b)
main()
|
def solve(a, b):
inf = 2 * 10 ** 6
d, n = inf, len(b)
for i in range(n):
if b[i] > 0:
{{completion}}
# b[i] > a[i]
if d < 0:
print("NO")
return
# All elements of b are 0s
if d == inf:
print("YES")
return
for i in range(n):
if a[i] - b[i] > d:
print("NO")
return
if b[i] > 0 and a[i] - b[i] < d:
print("NO")
return
# all a[i] - b[i] == d
print("YES")
def main():
from sys import stdin
from itertools import islice
tkns = map(int, stdin.read().split())
t = next(tkns)
for T in range(t):
n = next(tkns)
a, b = list(islice(tkns, n)), list(islice(tkns, n))
solve(a, b)
main()
|
d = min(d, a[i] - b[i])
|
[{"input": "6\n\n4\n\n3 5 4 1\n\n1 3 2 0\n\n3\n\n1 2 1\n\n0 1 0\n\n4\n\n5 3 7 2\n\n1 1 1 1\n\n5\n\n1 2 3 4 5\n\n1 2 3 4 6\n\n1\n\n8\n\n0\n\n1\n\n4\n\n6", "output": ["YES\nYES\nNO\nNO\nYES\nNO"]}]
|
block_completion_003931
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Kristina has two arrays $$$a$$$ and $$$b$$$, each containing $$$n$$$ non-negative integers. She can perform the following operation on array $$$a$$$ any number of times: apply a decrement to each non-zero element of the array, that is, replace the value of each element $$$a_i$$$ such that $$$a_i > 0$$$ with the value $$$a_i - 1$$$ ($$$1 \le i \le n$$$). If $$$a_i$$$ was $$$0$$$, its value does not change. Determine whether Kristina can get an array $$$b$$$ from an array $$$a$$$ in some number of operations (probably zero). In other words, can she make $$$a_i = b_i$$$ after some number of operations for each $$$1 \le i \le n$$$?For example, let $$$n = 4$$$, $$$a = [3, 5, 4, 1]$$$ and $$$b = [1, 3, 2, 0]$$$. In this case, she can apply the operation twice: after the first application of the operation she gets $$$a = [2, 4, 3, 0]$$$; after the second use of the operation she gets $$$a = [1, 3, 2, 0]$$$. Thus, in two operations, she can get an array $$$b$$$ from an array $$$a$$$.
Input Specification: The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β βthe number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$). The second line of each test case contains exactly $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ non-negative integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output on a separate line: YES, if by doing some number of operations it is possible to get an array $$$b$$$ from an array $$$a$$$; NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
Notes: NoteThe first test case is analyzed in the statement.In the second test case, it is enough to apply the operation to array $$$a$$$ once.In the third test case, it is impossible to get array $$$b$$$ from array $$$a$$$.
Code:
def solve(a, b):
inf = 2 * 10 ** 6
d, n = inf, len(b)
for i in range(n):
if b[i] > 0:
d = min(d, a[i] - b[i])
# b[i] > a[i]
if d < 0:
print("NO")
return
# All elements of b are 0s
if d == inf:
print("YES")
return
for i in range(n):
if a[i] - b[i] > d:
# TODO: Your code here
if b[i] > 0 and a[i] - b[i] < d:
print("NO")
return
# all a[i] - b[i] == d
print("YES")
def main():
from sys import stdin
from itertools import islice
tkns = map(int, stdin.read().split())
t = next(tkns)
for T in range(t):
n = next(tkns)
a, b = list(islice(tkns, n)), list(islice(tkns, n))
solve(a, b)
main()
|
def solve(a, b):
inf = 2 * 10 ** 6
d, n = inf, len(b)
for i in range(n):
if b[i] > 0:
d = min(d, a[i] - b[i])
# b[i] > a[i]
if d < 0:
print("NO")
return
# All elements of b are 0s
if d == inf:
print("YES")
return
for i in range(n):
if a[i] - b[i] > d:
{{completion}}
if b[i] > 0 and a[i] - b[i] < d:
print("NO")
return
# all a[i] - b[i] == d
print("YES")
def main():
from sys import stdin
from itertools import islice
tkns = map(int, stdin.read().split())
t = next(tkns)
for T in range(t):
n = next(tkns)
a, b = list(islice(tkns, n)), list(islice(tkns, n))
solve(a, b)
main()
|
print("NO")
return
|
[{"input": "6\n\n4\n\n3 5 4 1\n\n1 3 2 0\n\n3\n\n1 2 1\n\n0 1 0\n\n4\n\n5 3 7 2\n\n1 1 1 1\n\n5\n\n1 2 3 4 5\n\n1 2 3 4 6\n\n1\n\n8\n\n0\n\n1\n\n4\n\n6", "output": ["YES\nYES\nNO\nNO\nYES\nNO"]}]
|
block_completion_003932
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: An integer array $$$a_1, a_2, \ldots, a_n$$$ is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array: Choose any number $$$x$$$ from the array $$$a$$$, and any letter of the English alphabet $$$y$$$. Replace all occurrences of number $$$x$$$ with the letter $$$y$$$. For example, if we initially had an array $$$a = [2, 3, 2, 4, 1]$$$, then we could transform it the following way: Choose the number $$$2$$$ and the letter c. After that $$$a = [c, 3, c, 4, 1]$$$. Choose the number $$$3$$$ and the letter a. After that $$$a = [c, a, c, 4, 1]$$$. Choose the number $$$4$$$ and the letter t. After that $$$a = [c, a, c, t, 1]$$$. Choose the number $$$1$$$ and the letter a. After that $$$a = [c, a, c, t, a]$$$. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array $$$a$$$ and the string $$$s$$$ determine if the string $$$s$$$ could be got from the array $$$a$$$ after the described transformation?
Input Specification: The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3$$$) β the number of test cases. Then the description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) β the length of the array $$$a$$$ and the string $$$s$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$) β the elements of the array $$$a$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.
Output Specification: For each test case, output "YES", if we can get the string $$$s$$$ from the array $$$a$$$, and "NO" otherwise. You can output each letter in any case.
Notes: NoteThe first test case corresponds to the sample described in the statement.In the second test case we can choose the number $$$50$$$ and the letter a.In the third test case we can choose the number $$$11$$$ and the letter a, after that $$$a = [a, 22]$$$. Then we choose the number $$$22$$$ and the letter b and get $$$a = [a, b]$$$.In the fifth test case we can change all numbers one by one to the letter a.
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())
a = list(map(int, inp(n)))
s = list(inp1())
d = {}
ok = True
for i in range(n):
if a[i] not in d:
d[a[i]] = s[i]
elif d[a[i]] != s[i]:
# TODO: Your code here
print("YES" if ok else "NO")
|
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())
a = list(map(int, inp(n)))
s = list(inp1())
d = {}
ok = True
for i in range(n):
if a[i] not in d:
d[a[i]] = s[i]
elif d[a[i]] != s[i]:
{{completion}}
print("YES" if ok else "NO")
|
ok = not ok
break
|
[{"input": "7\n\n5\n\n2 3 2 4 1\n\ncacta\n\n1\n\n50\n\na\n\n2\n\n11 22\n\nab\n\n4\n\n1 2 2 1\n\naaab\n\n5\n\n1 2 3 2 1\n\naaaaa\n\n6\n\n1 10 2 9 3 8\n\nazzfdb\n\n7\n\n1 2 3 4 1 1 2\n\nabababb", "output": ["YES\nYES\nYES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004085
|
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 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':
last = cur
l.append(('g', i))
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:
# TODO: Your code here
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':
last = cur
l.append(('g', i))
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:
{{completion}}
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)
|
first_g = l[i][1]
|
[{"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_004148
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.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++).
Input Specification: The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) β the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) β the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) β elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.
Notes: NoteIn the first test case, the array $$$a = [2]$$$ after the first query.In the third test case, the array $$$a$$$ is modified as follows: $$$[1, 3, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[10, 12, 10, 12, 18, 56]$$$ $$$\rightarrow$$$ $$$[22, 24, 22, 24, 30, 68]$$$ $$$\rightarrow$$$ $$$[23, 25, 23, 25, 31, 69]$$$.
Code:
from itertools import islice
from sys import stdin
data = iter([int(x) for x in stdin.read().split()[1:]])
res = []
while True:
try:
n = next(data)
except StopIteration:
break
q = next(data)
counts = [0, 0]
sums = [0, 0]
for v in islice(data, n):
counts[v % 2] += 1
sums[v % 2] += v
for _ in range(q):
mod = next(data)
x = next(data)
to_add = counts[mod] * x
if x % 2:
counts[1 - mod] += counts[mod]
sums[1 - mod] += sums[mod] + to_add
counts[mod] = sums[mod] = 0
else:
# TODO: Your code here
res.append(sum(sums))
print('\n'.join(str(x) for x in res))
|
from itertools import islice
from sys import stdin
data = iter([int(x) for x in stdin.read().split()[1:]])
res = []
while True:
try:
n = next(data)
except StopIteration:
break
q = next(data)
counts = [0, 0]
sums = [0, 0]
for v in islice(data, n):
counts[v % 2] += 1
sums[v % 2] += v
for _ in range(q):
mod = next(data)
x = next(data)
to_add = counts[mod] * x
if x % 2:
counts[1 - mod] += counts[mod]
sums[1 - mod] += sums[mod] + to_add
counts[mod] = sums[mod] = 0
else:
{{completion}}
res.append(sum(sums))
print('\n'.join(str(x) for x in res))
|
sums[mod] += to_add
|
[{"input": "4\n\n1 1\n\n1\n\n1 1\n\n3 3\n\n1 2 4\n\n0 2\n\n1 3\n\n0 5\n\n6 7\n\n1 3 2 4 10 48\n\n1 6\n\n0 5\n\n0 4\n\n0 5\n\n1 3\n\n0 12\n\n0 1\n\n6 7\n\n1000000000 1000000000 1000000000 11 15 17\n\n0 17\n\n1 10000\n\n1 51\n\n0 92\n\n0 53\n\n1 16\n\n0 1", "output": ["2\n11\n14\n29\n80\n100\n100\n100\n118\n190\n196\n3000000094\n3000060094\n3000060400\n3000060952\n3000061270\n3000061366\n3000061366"]}]
|
block_completion_004172
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.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++).
Input Specification: The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) β the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) β the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) β elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.
Notes: NoteIn the first test case, the array $$$a = [2]$$$ after the first query.In the third test case, the array $$$a$$$ is modified as follows: $$$[1, 3, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[10, 12, 10, 12, 18, 56]$$$ $$$\rightarrow$$$ $$$[22, 24, 22, 24, 30, 68]$$$ $$$\rightarrow$$$ $$$[23, 25, 23, 25, 31, 69]$$$.
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():
return inp()[0]
t = inp1()
for _ in range(t):
n = inp1()
q = inp1()
a = inp(n)
tx = [inp(2) for _ in range(q)]
odd = 0
even = 0
for i in a:
if i % 2 == 0:
even +=1
else:
odd +=1
ret = sum(a)
for i in tx:
if i[0] == 0:
ret += even * i[1]
if i[1] % 2 != 0:
odd = n
even = 0
else:
ret += odd * i[1]
if i[1] % 2 != 0:
# TODO: Your code here
print(ret)
|
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():
return inp()[0]
t = inp1()
for _ in range(t):
n = inp1()
q = inp1()
a = inp(n)
tx = [inp(2) for _ in range(q)]
odd = 0
even = 0
for i in a:
if i % 2 == 0:
even +=1
else:
odd +=1
ret = sum(a)
for i in tx:
if i[0] == 0:
ret += even * i[1]
if i[1] % 2 != 0:
odd = n
even = 0
else:
ret += odd * i[1]
if i[1] % 2 != 0:
{{completion}}
print(ret)
|
even = n
odd = 0
|
[{"input": "4\n\n1 1\n\n1\n\n1 1\n\n3 3\n\n1 2 4\n\n0 2\n\n1 3\n\n0 5\n\n6 7\n\n1 3 2 4 10 48\n\n1 6\n\n0 5\n\n0 4\n\n0 5\n\n1 3\n\n0 12\n\n0 1\n\n6 7\n\n1000000000 1000000000 1000000000 11 15 17\n\n0 17\n\n1 10000\n\n1 51\n\n0 92\n\n0 53\n\n1 16\n\n0 1", "output": ["2\n11\n14\n29\n80\n100\n100\n100\n118\n190\n196\n3000000094\n3000060094\n3000060400\n3000060952\n3000061270\n3000061366\n3000061366"]}]
|
block_completion_004173
|
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: 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 line in [*open(0)][2::2]:
tot = 0
list = line.split(' ')
list2 = [0] + list
minv = int(list[0])
for val in range(len(list)-1):
diff = int(list2[val+1]) - int(list[val+1])
if (diff >= 0):
# TODO: Your code here
print(tot-minv+abs(minv)+int(list[len(list)-1]))
|
for line in [*open(0)][2::2]:
tot = 0
list = line.split(' ')
list2 = [0] + list
minv = int(list[0])
for val in range(len(list)-1):
diff = int(list2[val+1]) - int(list[val+1])
if (diff >= 0):
{{completion}}
print(tot-minv+abs(minv)+int(list[len(list)-1]))
|
tot += diff
minv -= diff
|
[{"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_004198
|
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 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();d=[a[0]]
for i in range(1,n):d.append(a[i]-a[i-1])
for i in range(1,n):
if d[i]<=0:# TODO: Your code here
print(sum(abs(i) for i in d))
|
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();d=[a[0]]
for i in range(1,n):d.append(a[i]-a[i-1])
for i in range(1,n):
if d[i]<=0:{{completion}}
print(sum(abs(i) for i in d))
|
d[0]+=d[i]
|
[{"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_004199
|
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())):
input()
a = [int(x) for x in input().split()]
prefix_value = a[0]
suffix_value = 0
steps = 0
for x, y in zip(a, a[1:]):
if x > y:
steps += x - y
prefix_value = y - suffix_value
elif y > x:
# TODO: Your code here
print(steps + abs(prefix_value))
|
for _ in range(int(input())):
input()
a = [int(x) for x in input().split()]
prefix_value = a[0]
suffix_value = 0
steps = 0
for x, y in zip(a, a[1:]):
if x > y:
steps += x - y
prefix_value = y - suffix_value
elif y > x:
{{completion}}
print(steps + abs(prefix_value))
|
steps += y - x
suffix_value += 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_004200
|
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:
from sys import stdin
a = int(stdin.readline())
for t in range(0,a):
b = int(stdin.readline())
c = stdin.readline().split()
count = 0
current = int(c[0])
for u in range(0,b-1):
if int(c[u+1])>int(c[u]):
count+=(int(c[u+1])-int(c[u]))
elif int(c[u+1]) < int(c[u]):
# TODO: Your code here
print(abs(current)+count)
|
from sys import stdin
a = int(stdin.readline())
for t in range(0,a):
b = int(stdin.readline())
c = stdin.readline().split()
count = 0
current = int(c[0])
for u in range(0,b-1):
if int(c[u+1])>int(c[u]):
count+=(int(c[u+1])-int(c[u]))
elif int(c[u+1]) < int(c[u]):
{{completion}}
print(abs(current)+count)
|
count+=(int(c[u]) - int(c[u+1]))
current = current - (int(c[u]) - int(c[u+1]))
|
[{"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_004201
|
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:
t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int,input().split()))
res,r = 0,0
for i in range(n-1):
x = A[i+1]-A[i]
if x>0:
# TODO: Your code here
res+=abs(x)
res+=abs(r-A[n-1])
print(res)
|
t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int,input().split()))
res,r = 0,0
for i in range(n-1):
x = A[i+1]-A[i]
if x>0:
{{completion}}
res+=abs(x)
res+=abs(r-A[n-1])
print(res)
|
r+=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_004202
|
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:
def solve():
n = int(input())
a = [int(i) for i in input().split()]
dl, dr = 0, 0
for i in range(1, n):
if a[i]-dr >= a[0]-dl:
dr += (a[i]-dr)-(a[0]-dl)
else:
# TODO: Your code here
return dl+dr+abs(a[0]-dl)
for _ in range(int(input())):
print(solve())
|
def solve():
n = int(input())
a = [int(i) for i in input().split()]
dl, dr = 0, 0
for i in range(1, n):
if a[i]-dr >= a[0]-dl:
dr += (a[i]-dr)-(a[0]-dl)
else:
{{completion}}
return dl+dr+abs(a[0]-dl)
for _ in range(int(input())):
print(solve())
|
dl += (a[0]-dl)-(a[i]-dr)
|
[{"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_004203
|
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:
v = int(input())
while v > 0:
n = int(input())
arr = input().split()
ori = int(arr[0])
temp = 0
ans = 0
x = 1
while x < n:
nex = int(arr[x])
ans += abs(nex - ori)
if nex - ori < 0:
# TODO: Your code here
ori = nex
x += 1
ans += abs(int(arr[0]) - temp)
print(ans)
v -= 1
|
v = int(input())
while v > 0:
n = int(input())
arr = input().split()
ori = int(arr[0])
temp = 0
ans = 0
x = 1
while x < n:
nex = int(arr[x])
ans += abs(nex - ori)
if nex - ori < 0:
{{completion}}
ori = nex
x += 1
ans += abs(int(arr[0]) - temp)
print(ans)
v -= 1
|
temp += abs(nex - ori)
|
[{"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_004204
|
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: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) β the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
# 1 0 0 1 0 0
# 0 1 0 0 0 1
# 1 1 1 2 2 2
# 0 1 1 1 1 2
# swap two same number is useless
# each time we swap i and i+1, only prefix of i is changed, either increased by 1 or decreased by 1
# same argument as of inversion, each time inversion can only increased by 1 or decreased by 1
# so in one step we can always move a prefix closer to the expected by 1
# Let s = sum(diff(prefix[a] - prefix[a'])) , we can always achive this in minimum time
# prefix + (0, 1) | (1,0)
# we would like to make every prefix of a is same as a' (with a' is fixed)
# when we swap pair (0,1) in two row, say we are at column j, then the prefix of one row decreased by 1 and the other is increased by 1 form the column j
# 1 1 1 0 0 0
# 0 0 0 1 1 1
# i
# Now let's construct array diff of two row
# Reprahsed of the problem
# In one step, we can either
# 1. increase / decrease any diff by 1
# 2. at a certain column, increase diff of either by 1 and decrease the other by 1 till the last column
# Analysis
# Go from the start since we have increamnt suffix operation
# If both element is same sign ,then add their abs since suffix operation not reduce their diff but also increase the total number of operatons, if on suffix operatons help the rest move closer to the target then we can just apply from the i+1 position to get the same result and take 1 less move
# If there are of different sign
# k = min(abs(row1[i]]), abs(row2[i])) normaly we would take k to make one ddiff move to zeros, but now with suffix opertions, we also move the other closer to 0 by k, so we are have free k more free operations, if this suffix make the rest worst then just apply k reverse suffix operation on i+1 to cancel the efffect so this algorithm always move to a better answer
n = int(input())
a, b, x, y = [list(map(int, input().split())) for _ in range(4)]
s0 = s1 = ans = 0
for m, n, p, q in zip(a, b, x, y):
s0 += m
s0 -= p
s1 += n
s1 -= q
while s0 > 0 and s1 < 0:
# TODO: Your code here
while s0 < 0 and s1 > 0:
ans += 1
s0 += 1
s1 -= 1
ans += abs(s0) + abs(s1)
print(-1 if s1 or s0 else ans) # finally but prefix must be 0
|
# 1 0 0 1 0 0
# 0 1 0 0 0 1
# 1 1 1 2 2 2
# 0 1 1 1 1 2
# swap two same number is useless
# each time we swap i and i+1, only prefix of i is changed, either increased by 1 or decreased by 1
# same argument as of inversion, each time inversion can only increased by 1 or decreased by 1
# so in one step we can always move a prefix closer to the expected by 1
# Let s = sum(diff(prefix[a] - prefix[a'])) , we can always achive this in minimum time
# prefix + (0, 1) | (1,0)
# we would like to make every prefix of a is same as a' (with a' is fixed)
# when we swap pair (0,1) in two row, say we are at column j, then the prefix of one row decreased by 1 and the other is increased by 1 form the column j
# 1 1 1 0 0 0
# 0 0 0 1 1 1
# i
# Now let's construct array diff of two row
# Reprahsed of the problem
# In one step, we can either
# 1. increase / decrease any diff by 1
# 2. at a certain column, increase diff of either by 1 and decrease the other by 1 till the last column
# Analysis
# Go from the start since we have increamnt suffix operation
# If both element is same sign ,then add their abs since suffix operation not reduce their diff but also increase the total number of operatons, if on suffix operatons help the rest move closer to the target then we can just apply from the i+1 position to get the same result and take 1 less move
# If there are of different sign
# k = min(abs(row1[i]]), abs(row2[i])) normaly we would take k to make one ddiff move to zeros, but now with suffix opertions, we also move the other closer to 0 by k, so we are have free k more free operations, if this suffix make the rest worst then just apply k reverse suffix operation on i+1 to cancel the efffect so this algorithm always move to a better answer
n = int(input())
a, b, x, y = [list(map(int, input().split())) for _ in range(4)]
s0 = s1 = ans = 0
for m, n, p, q in zip(a, b, x, y):
s0 += m
s0 -= p
s1 += n
s1 -= q
while s0 > 0 and s1 < 0:
{{completion}}
while s0 < 0 and s1 > 0:
ans += 1
s0 += 1
s1 -= 1
ans += abs(s0) + abs(s1)
print(-1 if s1 or s0 else ans) # finally but prefix must be 0
|
ans += 1
s0 -= 1
s1 += 1
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
block_completion_004255
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) β the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
# 1 0 0 1 0 0
# 0 1 0 0 0 1
# 1 1 1 2 2 2
# 0 1 1 1 1 2
# swap two same number is useless
# each time we swap i and i+1, only prefix of i is changed, either increased by 1 or decreased by 1
# same argument as of inversion, each time inversion can only increased by 1 or decreased by 1
# so in one step we can always move a prefix closer to the expected by 1
# Let s = sum(diff(prefix[a] - prefix[a'])) , we can always achive this in minimum time
# prefix + (0, 1) | (1,0)
# we would like to make every prefix of a is same as a' (with a' is fixed)
# when we swap pair (0,1) in two row, say we are at column j, then the prefix of one row decreased by 1 and the other is increased by 1 form the column j
# 1 1 1 0 0 0
# 0 0 0 1 1 1
# i
# Now let's construct array diff of two row
# Reprahsed of the problem
# In one step, we can either
# 1. increase / decrease any diff by 1
# 2. at a certain column, increase diff of either by 1 and decrease the other by 1 till the last column
# Analysis
# Go from the start since we have increamnt suffix operation
# If both element is same sign ,then add their abs since suffix operation not reduce their diff but also increase the total number of operatons, if on suffix operatons help the rest move closer to the target then we can just apply from the i+1 position to get the same result and take 1 less move
# If there are of different sign
# k = min(abs(row1[i]]), abs(row2[i])) normaly we would take k to make one ddiff move to zeros, but now with suffix opertions, we also move the other closer to 0 by k, so we are have free k more free operations, if this suffix make the rest worst then just apply k reverse suffix operation on i+1 to cancel the efffect so this algorithm always move to a better answer
n = int(input())
a, b, x, y = [list(map(int, input().split())) for _ in range(4)]
s0 = s1 = ans = 0
for m, n, p, q in zip(a, b, x, y):
s0 += m
s0 -= p
s1 += n
s1 -= q
while s0 > 0 and s1 < 0:
ans += 1
s0 -= 1
s1 += 1
while s0 < 0 and s1 > 0:
# TODO: Your code here
ans += abs(s0) + abs(s1)
print(-1 if s1 or s0 else ans) # finally but prefix must be 0
|
# 1 0 0 1 0 0
# 0 1 0 0 0 1
# 1 1 1 2 2 2
# 0 1 1 1 1 2
# swap two same number is useless
# each time we swap i and i+1, only prefix of i is changed, either increased by 1 or decreased by 1
# same argument as of inversion, each time inversion can only increased by 1 or decreased by 1
# so in one step we can always move a prefix closer to the expected by 1
# Let s = sum(diff(prefix[a] - prefix[a'])) , we can always achive this in minimum time
# prefix + (0, 1) | (1,0)
# we would like to make every prefix of a is same as a' (with a' is fixed)
# when we swap pair (0,1) in two row, say we are at column j, then the prefix of one row decreased by 1 and the other is increased by 1 form the column j
# 1 1 1 0 0 0
# 0 0 0 1 1 1
# i
# Now let's construct array diff of two row
# Reprahsed of the problem
# In one step, we can either
# 1. increase / decrease any diff by 1
# 2. at a certain column, increase diff of either by 1 and decrease the other by 1 till the last column
# Analysis
# Go from the start since we have increamnt suffix operation
# If both element is same sign ,then add their abs since suffix operation not reduce their diff but also increase the total number of operatons, if on suffix operatons help the rest move closer to the target then we can just apply from the i+1 position to get the same result and take 1 less move
# If there are of different sign
# k = min(abs(row1[i]]), abs(row2[i])) normaly we would take k to make one ddiff move to zeros, but now with suffix opertions, we also move the other closer to 0 by k, so we are have free k more free operations, if this suffix make the rest worst then just apply k reverse suffix operation on i+1 to cancel the efffect so this algorithm always move to a better answer
n = int(input())
a, b, x, y = [list(map(int, input().split())) for _ in range(4)]
s0 = s1 = ans = 0
for m, n, p, q in zip(a, b, x, y):
s0 += m
s0 -= p
s1 += n
s1 -= q
while s0 > 0 and s1 < 0:
ans += 1
s0 -= 1
s1 += 1
while s0 < 0 and s1 > 0:
{{completion}}
ans += abs(s0) + abs(s1)
print(-1 if s1 or s0 else ans) # finally but prefix must be 0
|
ans += 1
s0 += 1
s1 -= 1
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
block_completion_004256
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) β the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
n=int(input())
s=input()[::2],input()[::2]
t=input()[::2],input()[::2]
d=[0,0]
total=0
for y in range(n):
for x in 0,1:
d[x]+=(s[x][y]=="1")-(t[x][y]=="1")
if d[0]>0 and d[1]<0:
total+=1
d[0]-=1
d[1]+=1
elif d[0]<0 and d[1]>0:
# TODO: Your code here
total+=abs(d[0])+abs(d[1])
print(total if d==[0,0] else -1)
|
n=int(input())
s=input()[::2],input()[::2]
t=input()[::2],input()[::2]
d=[0,0]
total=0
for y in range(n):
for x in 0,1:
d[x]+=(s[x][y]=="1")-(t[x][y]=="1")
if d[0]>0 and d[1]<0:
total+=1
d[0]-=1
d[1]+=1
elif d[0]<0 and d[1]>0:
{{completion}}
total+=abs(d[0])+abs(d[1])
print(total if d==[0,0] else -1)
|
total+=1
d[0]+=1
d[1]-=1
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
block_completion_004257
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) β the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
def solve():
# Size of the matrices.
n = int(input())
# Data matrix (the first two rows correspond to the original matrix
# and the last two to the target matrix).
matrix = []
# Read the input data.
for _ in range(4):
matrix.append([int(data) for data in input().split()])
top = 0 # Difference between the prefixes of the first rows of the matrices.
bottom = 0 # Difference between the prefixes of the second rows of the matrices.
total = 0 # Total cost of the operations.
for i in range(n):
top += (matrix[0][i] - matrix[2][i]) # Update the first prefix.
bottom += (matrix[1][i] - matrix[3][i]) # Update the second prefix.
# If the prefix differences have different signs, swap the exceeding one
# in the positive row to the negative, spending an operation on it.
if bottom < 0 and 0 < top:
top -= 1
bottom += 1
total += 1
elif top < 0 and 0 < bottom:
# TODO: Your code here
# Update the total cost with the cost of fixing this prefix, since the last fix.
total += abs(top) + abs(bottom)
# The condition top + bottom == 0 is equivalent to top == 0 && bottom == 0, because top and
# bottom always have the same sign or at least one is zero.
# Therefore, if top + bottom != 0, then top != 0 or bottom != 0.
# This mean the matrices have different amount of one, so the problem is unsolvable.
if top + bottom != 0:
return -1
# Otherwise, the problem has a solution, and it's the total calculated cost.
return total
print(solve())
|
def solve():
# Size of the matrices.
n = int(input())
# Data matrix (the first two rows correspond to the original matrix
# and the last two to the target matrix).
matrix = []
# Read the input data.
for _ in range(4):
matrix.append([int(data) for data in input().split()])
top = 0 # Difference between the prefixes of the first rows of the matrices.
bottom = 0 # Difference between the prefixes of the second rows of the matrices.
total = 0 # Total cost of the operations.
for i in range(n):
top += (matrix[0][i] - matrix[2][i]) # Update the first prefix.
bottom += (matrix[1][i] - matrix[3][i]) # Update the second prefix.
# If the prefix differences have different signs, swap the exceeding one
# in the positive row to the negative, spending an operation on it.
if bottom < 0 and 0 < top:
top -= 1
bottom += 1
total += 1
elif top < 0 and 0 < bottom:
{{completion}}
# Update the total cost with the cost of fixing this prefix, since the last fix.
total += abs(top) + abs(bottom)
# The condition top + bottom == 0 is equivalent to top == 0 && bottom == 0, because top and
# bottom always have the same sign or at least one is zero.
# Therefore, if top + bottom != 0, then top != 0 or bottom != 0.
# This mean the matrices have different amount of one, so the problem is unsolvable.
if top + bottom != 0:
return -1
# Otherwise, the problem has a solution, and it's the total calculated cost.
return total
print(solve())
|
top += 1
bottom -= 1
total += 1
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
block_completion_004258
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) β the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
import time
def main():
n = int(input())
curr = [[int(x) for x in input().split(" ")] for _ in range(2)]
want = [[int(x) for x in input().split(" ")] for _ in range(2)]
out = 0
s1 = 0
s2 = 0
for x in range(n):
out += abs(s1) + abs(s2)
s1 += curr[0][x]
s2 += curr[1][x]
s1 -= want[0][x]
s2 -= want[1][x]
if abs(s1 + s2) < abs(s1) + abs(s2):
if abs(s1) <= abs(s2):
out += abs(s1)
s2 += s1
s1 = 0
else:
# TODO: Your code here
if s1 != 0 or s2 != 0:
print(-1)
else:
print(out)
if __name__ == "__main__":
main()
|
import time
def main():
n = int(input())
curr = [[int(x) for x in input().split(" ")] for _ in range(2)]
want = [[int(x) for x in input().split(" ")] for _ in range(2)]
out = 0
s1 = 0
s2 = 0
for x in range(n):
out += abs(s1) + abs(s2)
s1 += curr[0][x]
s2 += curr[1][x]
s1 -= want[0][x]
s2 -= want[1][x]
if abs(s1 + s2) < abs(s1) + abs(s2):
if abs(s1) <= abs(s2):
out += abs(s1)
s2 += s1
s1 = 0
else:
{{completion}}
if s1 != 0 or s2 != 0:
print(-1)
else:
print(out)
if __name__ == "__main__":
main()
|
out += abs(s2)
s1 += s2
s2 = 0
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
block_completion_004259
|
block
|
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:
import math
lines = [*open(0)]
sizes = lines[1].split(' ')
tot, running = 0, 0
minval = 0
for lock in sizes:
tot += int(lock)
running += 1
minval = max(minval, tot/running)
for mintime in lines[3:]:
if (int(mintime) < minval):
print("-1")
else:
# TODO: Your code here
|
import math
lines = [*open(0)]
sizes = lines[1].split(' ')
tot, running = 0, 0
minval = 0
for lock in sizes:
tot += int(lock)
running += 1
minval = max(minval, tot/running)
for mintime in lines[3:]:
if (int(mintime) < minval):
print("-1")
else:
{{completion}}
|
print(math.ceil(tot/int(mintime)))
|
[{"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_004263
|
block
|
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:
I=input;n=int(I());p=m=0
for i,v in enumerate(I().split()):
# TODO: Your code here
for _ in [0]*int(I()):
t=int(I());print([-1,(p+t-1)//t][t>=m])
|
I=input;n=int(I());p=m=0
for i,v in enumerate(I().split()):
{{completion}}
for _ in [0]*int(I()):
t=int(I());print([-1,(p+t-1)//t][t>=m])
|
p+=int(v);m=max(m,(p+i)//(i+1))
|
[{"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_004264
|
block
|
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:
I=input;n=int(I());p=m=0
for i,v in enumerate(I().split()):
p+=int(v);m=max(m,(p+i)//(i+1))
for _ in [0]*int(I()):
# TODO: Your code here
|
I=input;n=int(I());p=m=0
for i,v in enumerate(I().split()):
p+=int(v);m=max(m,(p+i)//(i+1))
for _ in [0]*int(I()):
{{completion}}
|
t=int(I());print([-1,(p+t-1)//t][t>=m])
|
[{"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_004265
|
block
|
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:
import math as ma
r = range
R = lambda: int(input())
num_of_locks = R()
vols_arr = list(map(int, input().split(" ")))
sum_of_vols = 0
avg_vols = []
for _ in r(len(vols_arr)): sum_of_vols += vols_arr[_]; avg_vols += ma.ceil(sum_of_vols/(_ + 1)),
max_avg_vols = max(avg_vols)
for _ in r(R()):
liters = R(); answer = ma.ceil(sum_of_vols/liters)
if max_avg_vols > liters:
# TODO: Your code here
print(answer)
|
import math as ma
r = range
R = lambda: int(input())
num_of_locks = R()
vols_arr = list(map(int, input().split(" ")))
sum_of_vols = 0
avg_vols = []
for _ in r(len(vols_arr)): sum_of_vols += vols_arr[_]; avg_vols += ma.ceil(sum_of_vols/(_ + 1)),
max_avg_vols = max(avg_vols)
for _ in r(R()):
liters = R(); answer = ma.ceil(sum_of_vols/liters)
if max_avg_vols > liters:
{{completion}}
print(answer)
|
answer = -1
|
[{"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_004266
|
block
|
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:
n = int(input())
a = list(map(int, input().split()))
maxi = tot = 0
for i, j in enumerate(a, 1):
tot += j
maxi = max(maxi, (tot+i-1) // i)
q = int(input())
for _ in range(q):
k = int(input())
if k < maxi:
print(-1)
else:
# open x pipe
# time = ceil(sum / x) => x increased => time decrease
# => sum <= x * time -> x >= sum / time -> x = ceil(sum / time) (looking for x min)
# TODO: Your code here
|
n = int(input())
a = list(map(int, input().split()))
maxi = tot = 0
for i, j in enumerate(a, 1):
tot += j
maxi = max(maxi, (tot+i-1) // i)
q = int(input())
for _ in range(q):
k = int(input())
if k < maxi:
print(-1)
else:
# open x pipe
# time = ceil(sum / x) => x increased => time decrease
# => sum <= x * time -> x >= sum / time -> x = ceil(sum / time) (looking for x min)
{{completion}}
|
print((tot + k - 1) // k)
|
[{"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_004267
|
block
|
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: 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:
import itertools
m=0
n = int(input())
v = list(itertools.accumulate(map(int, input().split())))
for i in range(n):
# TODO: Your code here
for _ in range(int(input())):
t = int(input())
print((v[-1] - 1) // t + 1 if t >= m else -1)
|
import itertools
m=0
n = int(input())
v = list(itertools.accumulate(map(int, input().split())))
for i in range(n):
{{completion}}
for _ in range(int(input())):
t = int(input())
print((v[-1] - 1) // t + 1 if t >= m else -1)
|
m=max((v[i]-1)//(i+1)+1,m)
|
[{"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_004269
|
block
|
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:
import itertools
m=0
n = int(input())
v = list(itertools.accumulate(map(int, input().split())))
for i in range(n):
m=max((v[i]-1)//(i+1)+1,m)
for _ in range(int(input())):
# TODO: Your code here
|
import itertools
m=0
n = int(input())
v = list(itertools.accumulate(map(int, input().split())))
for i in range(n):
m=max((v[i]-1)//(i+1)+1,m)
for _ in range(int(input())):
{{completion}}
|
t = int(input())
print((v[-1] - 1) // t + 1 if t >= m else -1)
|
[{"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_004270
|
block
|
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:
number = int(input())
V = [int(i) for i in input().split()]
time,total = 0,0
for i in range(number):
total += V[i]
time = max(time,(total+i)//(i+1))
pass
for q in range(int(input())):
t = int(input())
if(t<time): print(-1)
else: # TODO: Your code here
pass
|
number = int(input())
V = [int(i) for i in input().split()]
time,total = 0,0
for i in range(number):
total += V[i]
time = max(time,(total+i)//(i+1))
pass
for q in range(int(input())):
t = int(input())
if(t<time): print(-1)
else: {{completion}}
pass
|
print((total+t-1)//t)
|
[{"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_004271
|
block
|
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(val > max): # TODO: Your code here
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(val > max): {{completion}}
for _ in r(i()): t = i();print(ceil(sum/t)) if(max <= t) else print(-1)
|
max = val
|
[{"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_004272
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.
Input Specification: In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) β table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$). It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.
Output Specification: Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.
Notes: NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.
Code:
#from math import ceil, floor, gcd, log
#import heapq as hq
#from collections import defaultdict as dd
#mydd=dd(list) for .append
#from collections import deque as dq #deque e.g. myqueue=dq(list)
#append/appendleft/appendright/pop/popleft
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split()))) #.split(','), default is space
#def insr():
# s = input()
# return(list(s[:len(s) - 1]))
#def invr():
# return(map(int,input().split()))
####################################################
#1) inp β For taking integer inputs.
#2) inlt β For taking List inputs.
#3) insr β For taking string inputs. Returns a List of Characters.
#4) invr β For taking space seperated integer variable inputs.
####################################################
def swp(x1,x2):
tmp=a[x1[0]][x1[1]]
a[x1[0]][x1[1]]=a[x2[0]][x2[1]]
a[x2[0]][x2[1]]=tmp
def fnei(xlst):
tmpl=[xlst]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def fnei2(xlst):
tmpl=[]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def chkb(x,y):
if a[x][y]==1:return False
for i in fnei2([x,y]):
if a[x][y]>a[i[0]][i[1]]:
return False
else:
return True
#######################
t=1
#t = int(input())
for tc in range(t):
n,m = map(int, input().split())
# n=inp()
# a=inlt()
# s=insr()
# occ=dict();
# for i in range(n):occ[i]=[]
# for i in range(n):
# occ[i].append(inlt())
a=[]
for i in range(n):
a.append(inlt())
b=[]
for i in range(n):
for j in range(m):
if chkb(i,j):b.append([i,j])
if len(b)==0:print(0);continue
if len(b)>2:print(2);continue
cter=0
bnei=fnei(b[0])
for j in bnei:
for i1 in range(n):
for i2 in range(m):
i=[i1,i2]
if i==b[0]:continue
# print(a,a[i[0]][i[1]],a[j[0]][j[1]])
swp(i,j)
flag=1
for k in fnei(i)+fnei(j):
if chkb(k[0],k[1]):flag=0;break
if len(b)>1:
for k2 in range(1,len(b)):
if chkb(b[k2][0],b[k2][1]):# TODO: Your code here
swp(i,j)
# print(a,i,j)
if flag:cter+=1;#print('success',i,j)
if cter==0: # all single move efforts failed
print(2)
else:
print(1,cter)
#print(*a2,sep=' ')
#print(" ".join(str(i) for i in a2))
#prefixsum a=[a1...an] #psa=[0]*(n+1)
#for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x]
|
#from math import ceil, floor, gcd, log
#import heapq as hq
#from collections import defaultdict as dd
#mydd=dd(list) for .append
#from collections import deque as dq #deque e.g. myqueue=dq(list)
#append/appendleft/appendright/pop/popleft
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split()))) #.split(','), default is space
#def insr():
# s = input()
# return(list(s[:len(s) - 1]))
#def invr():
# return(map(int,input().split()))
####################################################
#1) inp β For taking integer inputs.
#2) inlt β For taking List inputs.
#3) insr β For taking string inputs. Returns a List of Characters.
#4) invr β For taking space seperated integer variable inputs.
####################################################
def swp(x1,x2):
tmp=a[x1[0]][x1[1]]
a[x1[0]][x1[1]]=a[x2[0]][x2[1]]
a[x2[0]][x2[1]]=tmp
def fnei(xlst):
tmpl=[xlst]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def fnei2(xlst):
tmpl=[]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def chkb(x,y):
if a[x][y]==1:return False
for i in fnei2([x,y]):
if a[x][y]>a[i[0]][i[1]]:
return False
else:
return True
#######################
t=1
#t = int(input())
for tc in range(t):
n,m = map(int, input().split())
# n=inp()
# a=inlt()
# s=insr()
# occ=dict();
# for i in range(n):occ[i]=[]
# for i in range(n):
# occ[i].append(inlt())
a=[]
for i in range(n):
a.append(inlt())
b=[]
for i in range(n):
for j in range(m):
if chkb(i,j):b.append([i,j])
if len(b)==0:print(0);continue
if len(b)>2:print(2);continue
cter=0
bnei=fnei(b[0])
for j in bnei:
for i1 in range(n):
for i2 in range(m):
i=[i1,i2]
if i==b[0]:continue
# print(a,a[i[0]][i[1]],a[j[0]][j[1]])
swp(i,j)
flag=1
for k in fnei(i)+fnei(j):
if chkb(k[0],k[1]):flag=0;break
if len(b)>1:
for k2 in range(1,len(b)):
if chkb(b[k2][0],b[k2][1]):{{completion}}
swp(i,j)
# print(a,i,j)
if flag:cter+=1;#print('success',i,j)
if cter==0: # all single move efforts failed
print(2)
else:
print(1,cter)
#print(*a2,sep=' ')
#print(" ".join(str(i) for i in a2))
#prefixsum a=[a1...an] #psa=[0]*(n+1)
#for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x]
|
flag=0;break
|
[{"input": "3 3\n2 1 3\n6 7 4\n9 8 5", "output": ["0"]}, {"input": "2 3\n1 6 4\n3 2 5", "output": ["1 3"]}, {"input": "1 6\n1 6 5 4 3 2", "output": ["2"]}]
|
block_completion_004307
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.
Input Specification: In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) β table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$). It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.
Output Specification: Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.
Notes: NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.
Code:
#from math import ceil, floor, gcd, log
#import heapq as hq
#from collections import defaultdict as dd
#mydd=dd(list) for .append
#from collections import deque as dq #deque e.g. myqueue=dq(list)
#append/appendleft/appendright/pop/popleft
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split()))) #.split(','), default is space
#def insr():
# s = input()
# return(list(s[:len(s) - 1]))
#def invr():
# return(map(int,input().split()))
####################################################
#1) inp β For taking integer inputs.
#2) inlt β For taking List inputs.
#3) insr β For taking string inputs. Returns a List of Characters.
#4) invr β For taking space seperated integer variable inputs.
####################################################
def swp(x1,x2):
tmp=a[x1[0]][x1[1]]
a[x1[0]][x1[1]]=a[x2[0]][x2[1]]
a[x2[0]][x2[1]]=tmp
def fnei(xlst):
tmpl=[xlst]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def fnei2(xlst):
tmpl=[]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def chkb(x,y):
if a[x][y]==1:return False
for i in fnei2([x,y]):
if a[x][y]>a[i[0]][i[1]]:
return False
else:
return True
#######################
t=1
#t = int(input())
for tc in range(t):
n,m = map(int, input().split())
# n=inp()
# a=inlt()
# s=insr()
# occ=dict();
# for i in range(n):occ[i]=[]
# for i in range(n):
# occ[i].append(inlt())
a=[]
for i in range(n):
a.append(inlt())
b=[]
for i in range(n):
for j in range(m):
if chkb(i,j):b.append([i,j])
if len(b)==0:print(0);continue
if len(b)>2:print(2);continue
cter=0
bnei=fnei(b[0])
for j in bnei:
for i1 in range(n):
for i2 in range(m):
i=[i1,i2]
if i==b[0]:continue
# print(a,a[i[0]][i[1]],a[j[0]][j[1]])
swp(i,j)
flag=1
for k in fnei(i)+fnei(j):
if chkb(k[0],k[1]):# TODO: Your code here
if len(b)>1:
for k2 in range(1,len(b)):
if chkb(b[k2][0],b[k2][1]):flag=0;break
swp(i,j)
# print(a,i,j)
if flag:cter+=1;#print('success',i,j)
if cter==0: # all single move efforts failed
print(2)
else:
print(1,cter)
#print(*a2,sep=' ')
#print(" ".join(str(i) for i in a2))
#prefixsum a=[a1...an] #psa=[0]*(n+1)
#for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x]
|
#from math import ceil, floor, gcd, log
#import heapq as hq
#from collections import defaultdict as dd
#mydd=dd(list) for .append
#from collections import deque as dq #deque e.g. myqueue=dq(list)
#append/appendleft/appendright/pop/popleft
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split()))) #.split(','), default is space
#def insr():
# s = input()
# return(list(s[:len(s) - 1]))
#def invr():
# return(map(int,input().split()))
####################################################
#1) inp β For taking integer inputs.
#2) inlt β For taking List inputs.
#3) insr β For taking string inputs. Returns a List of Characters.
#4) invr β For taking space seperated integer variable inputs.
####################################################
def swp(x1,x2):
tmp=a[x1[0]][x1[1]]
a[x1[0]][x1[1]]=a[x2[0]][x2[1]]
a[x2[0]][x2[1]]=tmp
def fnei(xlst):
tmpl=[xlst]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def fnei2(xlst):
tmpl=[]
if xlst[0]>0:tmpl.append([xlst[0]-1,xlst[1]])
if xlst[1]>0:tmpl.append([xlst[0],xlst[1]-1])
if xlst[0]<n-1:tmpl.append([xlst[0]+1,xlst[1]])
if xlst[1]<m-1:tmpl.append([xlst[0],xlst[1]+1])
return tmpl
def chkb(x,y):
if a[x][y]==1:return False
for i in fnei2([x,y]):
if a[x][y]>a[i[0]][i[1]]:
return False
else:
return True
#######################
t=1
#t = int(input())
for tc in range(t):
n,m = map(int, input().split())
# n=inp()
# a=inlt()
# s=insr()
# occ=dict();
# for i in range(n):occ[i]=[]
# for i in range(n):
# occ[i].append(inlt())
a=[]
for i in range(n):
a.append(inlt())
b=[]
for i in range(n):
for j in range(m):
if chkb(i,j):b.append([i,j])
if len(b)==0:print(0);continue
if len(b)>2:print(2);continue
cter=0
bnei=fnei(b[0])
for j in bnei:
for i1 in range(n):
for i2 in range(m):
i=[i1,i2]
if i==b[0]:continue
# print(a,a[i[0]][i[1]],a[j[0]][j[1]])
swp(i,j)
flag=1
for k in fnei(i)+fnei(j):
if chkb(k[0],k[1]):{{completion}}
if len(b)>1:
for k2 in range(1,len(b)):
if chkb(b[k2][0],b[k2][1]):flag=0;break
swp(i,j)
# print(a,i,j)
if flag:cter+=1;#print('success',i,j)
if cter==0: # all single move efforts failed
print(2)
else:
print(1,cter)
#print(*a2,sep=' ')
#print(" ".join(str(i) for i in a2))
#prefixsum a=[a1...an] #psa=[0]*(n+1)
#for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x]
|
flag=0;break
|
[{"input": "3 3\n2 1 3\n6 7 4\n9 8 5", "output": ["0"]}, {"input": "2 3\n1 6 4\n3 2 5", "output": ["1 3"]}, {"input": "1 6\n1 6 5 4 3 2", "output": ["2"]}]
|
block_completion_004308
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.
Input Specification: In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) β table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$). It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.
Output Specification: Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.
Notes: NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.
Code:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from itertools import chain
def near(r, c, itself = False):
if itself:
yield (r, c)
if 0 < r:
yield (r - 1, c)
if r + 1 < n:
yield (r + 1, c)
if 0 < c:
yield (r, c - 1)
if c + 1 < m:
yield (r, c + 1)
# R = []
# if itself:
# R.append((r, c))
# if 0 < r:
# R.append((r - 1, c))
# if r + 1 < n:
# R.append((r + 1, c))
# if 0 < c:
# R.append((r, c - 1))
# if c + 1 < m:
# R.append((r, c + 1))
# return R
def ok(x, y):
v = A[x][y]
if v == 1:
return True
return any(A[r][c] < v for r, c in near(x, y))
def swapAndCheck(r1, c1, r2, c2):
if (r1 , c1) != (r2, c2):
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
flag = ok(r1, c1) and ok(r2, c2) and all(ok(r, c) for r, c in chain(near(r1, c1), near(r2, c2), H[1:]))
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
return flag
return False
n, m = map(int, input().split())
A = []
for _ in range(n):
A.append(list(map(int, input().split())))
H = list({(r, c) for r in range(n) for c in range(m) if not ok(r, c)})
if not H:
print("0")
elif len(H) > 2:
print("2")
else:
r1, c1 = H[0]
w = 0
for r, c in near(r1, c1, True):
for x in range(n):
for y in range(m):
if (r1 != x or c1 != y) and swapAndCheck(r, c, x, y):
# TODO: Your code here
if w != 0:
print("1 {}".format(w))
else:
print("2")
|
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from itertools import chain
def near(r, c, itself = False):
if itself:
yield (r, c)
if 0 < r:
yield (r - 1, c)
if r + 1 < n:
yield (r + 1, c)
if 0 < c:
yield (r, c - 1)
if c + 1 < m:
yield (r, c + 1)
# R = []
# if itself:
# R.append((r, c))
# if 0 < r:
# R.append((r - 1, c))
# if r + 1 < n:
# R.append((r + 1, c))
# if 0 < c:
# R.append((r, c - 1))
# if c + 1 < m:
# R.append((r, c + 1))
# return R
def ok(x, y):
v = A[x][y]
if v == 1:
return True
return any(A[r][c] < v for r, c in near(x, y))
def swapAndCheck(r1, c1, r2, c2):
if (r1 , c1) != (r2, c2):
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
flag = ok(r1, c1) and ok(r2, c2) and all(ok(r, c) for r, c in chain(near(r1, c1), near(r2, c2), H[1:]))
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
return flag
return False
n, m = map(int, input().split())
A = []
for _ in range(n):
A.append(list(map(int, input().split())))
H = list({(r, c) for r in range(n) for c in range(m) if not ok(r, c)})
if not H:
print("0")
elif len(H) > 2:
print("2")
else:
r1, c1 = H[0]
w = 0
for r, c in near(r1, c1, True):
for x in range(n):
for y in range(m):
if (r1 != x or c1 != y) and swapAndCheck(r, c, x, y):
{{completion}}
if w != 0:
print("1 {}".format(w))
else:
print("2")
|
w += 1
|
[{"input": "3 3\n2 1 3\n6 7 4\n9 8 5", "output": ["0"]}, {"input": "2 3\n1 6 4\n3 2 5", "output": ["1 3"]}, {"input": "1 6\n1 6 5 4 3 2", "output": ["2"]}]
|
block_completion_004309
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.
Input Specification: In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) β table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$). It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.
Output Specification: Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.
Notes: NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.
Code:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
# TODO: Your code here
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from itertools import chain
def near(r, c, itself = False):
if itself:
yield (r, c)
if 0 < r:
yield (r - 1, c)
if r + 1 < n:
yield (r + 1, c)
if 0 < c:
yield (r, c - 1)
if c + 1 < m:
yield (r, c + 1)
# R = []
# if itself:
# R.append((r, c))
# if 0 < r:
# R.append((r - 1, c))
# if r + 1 < n:
# R.append((r + 1, c))
# if 0 < c:
# R.append((r, c - 1))
# if c + 1 < m:
# R.append((r, c + 1))
# return R
def ok(x, y):
v = A[x][y]
if v == 1:
return True
return any(A[r][c] < v for r, c in near(x, y))
def swapAndCheck(r1, c1, r2, c2):
if (r1 , c1) != (r2, c2):
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
flag = ok(r1, c1) and ok(r2, c2) and all(ok(r, c) for r, c in chain(near(r1, c1), near(r2, c2), H[1:]))
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
return flag
return False
n, m = map(int, input().split())
A = []
for _ in range(n):
A.append(list(map(int, input().split())))
H = list({(r, c) for r in range(n) for c in range(m) if not ok(r, c)})
if not H:
print("0")
elif len(H) > 2:
print("2")
else:
r1, c1 = H[0]
w = 0
for r, c in near(r1, c1, True):
for x in range(n):
for y in range(m):
if (r1 != x or c1 != y) and swapAndCheck(r, c, x, y):
w += 1
if w != 0:
print("1 {}".format(w))
else:
print("2")
|
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
{{completion}}
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from itertools import chain
def near(r, c, itself = False):
if itself:
yield (r, c)
if 0 < r:
yield (r - 1, c)
if r + 1 < n:
yield (r + 1, c)
if 0 < c:
yield (r, c - 1)
if c + 1 < m:
yield (r, c + 1)
# R = []
# if itself:
# R.append((r, c))
# if 0 < r:
# R.append((r - 1, c))
# if r + 1 < n:
# R.append((r + 1, c))
# if 0 < c:
# R.append((r, c - 1))
# if c + 1 < m:
# R.append((r, c + 1))
# return R
def ok(x, y):
v = A[x][y]
if v == 1:
return True
return any(A[r][c] < v for r, c in near(x, y))
def swapAndCheck(r1, c1, r2, c2):
if (r1 , c1) != (r2, c2):
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
flag = ok(r1, c1) and ok(r2, c2) and all(ok(r, c) for r, c in chain(near(r1, c1), near(r2, c2), H[1:]))
A[r1][c1], A[r2][c2] = A[r2][c2], A[r1][c1]
return flag
return False
n, m = map(int, input().split())
A = []
for _ in range(n):
A.append(list(map(int, input().split())))
H = list({(r, c) for r in range(n) for c in range(m) if not ok(r, c)})
if not H:
print("0")
elif len(H) > 2:
print("2")
else:
r1, c1 = H[0]
w = 0
for r, c in near(r1, c1, True):
for x in range(n):
for y in range(m):
if (r1 != x or c1 != y) and swapAndCheck(r, c, x, y):
w += 1
if w != 0:
print("1 {}".format(w))
else:
print("2")
|
break
|
[{"input": "3 3\n2 1 3\n6 7 4\n9 8 5", "output": ["0"]}, {"input": "2 3\n1 6 4\n3 2 5", "output": ["1 3"]}, {"input": "1 6\n1 6 5 4 3 2", "output": ["2"]}]
|
block_completion_004310
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.
Input Specification: In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) β table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$). It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.
Output Specification: Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.
Notes: NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.
Code:
import os
import sys
from io import BytesIO, IOBase
#_str = str
#str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def main():
n, m = list(map(int, input().strip().split(' ')))
g = [list(map(int, input().strip().split(' '))) for _ in range(n)]
bfs = set()
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def check(x, y):
if g[x][y] == 1:
return True
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and g[x][y] > g[nx][ny]:
return True
return False
def check5(x, y):
if not check(x, y):
return False
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and not check(nx, ny):
return False
return True
bad = list()
for x in range(n):
for y in range(m):
if g[x][y] == 1:
continue
if not check(x, y):
bad.append([x, y])
if not bad:
print(0)
elif len(bad) > 5:
print(2)
else:
candidate = [bad[0]]
for i in range(4):
nx, ny = bad[0][0] + dx[i], bad[0][1] + dy[i]
if 0 <= nx < n and 0 <= ny < m:
candidate.append([nx, ny])
res = 0
for cx, cy in candidate:
for x in range(n):
for y in range(m):
if x == bad[0][0] and y == bad[0][1]:
continue
if cx == x and cy == y:
continue
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
flag = True
for bx, by in bad:
if not check(bx, by):
# TODO: Your code here
if flag and check5(x, y) and check5(cx, cy):
res += 1
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
if res == 0:
print(2)
else:
print(1, res)
return
main()
|
import os
import sys
from io import BytesIO, IOBase
#_str = str
#str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def main():
n, m = list(map(int, input().strip().split(' ')))
g = [list(map(int, input().strip().split(' '))) for _ in range(n)]
bfs = set()
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def check(x, y):
if g[x][y] == 1:
return True
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and g[x][y] > g[nx][ny]:
return True
return False
def check5(x, y):
if not check(x, y):
return False
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and not check(nx, ny):
return False
return True
bad = list()
for x in range(n):
for y in range(m):
if g[x][y] == 1:
continue
if not check(x, y):
bad.append([x, y])
if not bad:
print(0)
elif len(bad) > 5:
print(2)
else:
candidate = [bad[0]]
for i in range(4):
nx, ny = bad[0][0] + dx[i], bad[0][1] + dy[i]
if 0 <= nx < n and 0 <= ny < m:
candidate.append([nx, ny])
res = 0
for cx, cy in candidate:
for x in range(n):
for y in range(m):
if x == bad[0][0] and y == bad[0][1]:
continue
if cx == x and cy == y:
continue
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
flag = True
for bx, by in bad:
if not check(bx, by):
{{completion}}
if flag and check5(x, y) and check5(cx, cy):
res += 1
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
if res == 0:
print(2)
else:
print(1, res)
return
main()
|
flag = False
break
|
[{"input": "3 3\n2 1 3\n6 7 4\n9 8 5", "output": ["0"]}, {"input": "2 3\n1 6 4\n3 2 5", "output": ["1 3"]}, {"input": "1 6\n1 6 5 4 3 2", "output": ["2"]}]
|
block_completion_004311
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.
Input Specification: In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) β table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$). It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.
Output Specification: Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.
Notes: NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.
Code:
import os
import sys
from io import BytesIO, IOBase
#_str = str
#str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def main():
n, m = list(map(int, input().strip().split(' ')))
g = [list(map(int, input().strip().split(' '))) for _ in range(n)]
bfs = set()
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def check(x, y):
if g[x][y] == 1:
return True
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and g[x][y] > g[nx][ny]:
return True
return False
def check5(x, y):
if not check(x, y):
return False
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and not check(nx, ny):
return False
return True
bad = list()
for x in range(n):
for y in range(m):
if g[x][y] == 1:
continue
if not check(x, y):
bad.append([x, y])
if not bad:
print(0)
elif len(bad) > 5:
print(2)
else:
candidate = [bad[0]]
for i in range(4):
nx, ny = bad[0][0] + dx[i], bad[0][1] + dy[i]
if 0 <= nx < n and 0 <= ny < m:
candidate.append([nx, ny])
res = 0
for cx, cy in candidate:
for x in range(n):
for y in range(m):
if x == bad[0][0] and y == bad[0][1]:
# TODO: Your code here
if cx == x and cy == y:
continue
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
flag = True
for bx, by in bad:
if not check(bx, by):
flag = False
break
if flag and check5(x, y) and check5(cx, cy):
res += 1
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
if res == 0:
print(2)
else:
print(1, res)
return
main()
|
import os
import sys
from io import BytesIO, IOBase
#_str = str
#str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def main():
n, m = list(map(int, input().strip().split(' ')))
g = [list(map(int, input().strip().split(' '))) for _ in range(n)]
bfs = set()
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def check(x, y):
if g[x][y] == 1:
return True
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and g[x][y] > g[nx][ny]:
return True
return False
def check5(x, y):
if not check(x, y):
return False
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and not check(nx, ny):
return False
return True
bad = list()
for x in range(n):
for y in range(m):
if g[x][y] == 1:
continue
if not check(x, y):
bad.append([x, y])
if not bad:
print(0)
elif len(bad) > 5:
print(2)
else:
candidate = [bad[0]]
for i in range(4):
nx, ny = bad[0][0] + dx[i], bad[0][1] + dy[i]
if 0 <= nx < n and 0 <= ny < m:
candidate.append([nx, ny])
res = 0
for cx, cy in candidate:
for x in range(n):
for y in range(m):
if x == bad[0][0] and y == bad[0][1]:
{{completion}}
if cx == x and cy == y:
continue
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
flag = True
for bx, by in bad:
if not check(bx, by):
flag = False
break
if flag and check5(x, y) and check5(cx, cy):
res += 1
g[cx][cy], g[x][y] = g[x][y], g[cx][cy]
if res == 0:
print(2)
else:
print(1, res)
return
main()
|
continue
|
[{"input": "3 3\n2 1 3\n6 7 4\n9 8 5", "output": ["0"]}, {"input": "2 3\n1 6 4\n3 2 5", "output": ["1 3"]}, {"input": "1 6\n1 6 5 4 3 2", "output": ["2"]}]
|
block_completion_004312
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Lena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of $$$n$$$ rows and $$$m$$$ columns, and each cell is either black or white. The coordinates $$$(i,j)$$$ denote the cell which belongs to the $$$i$$$-th row and $$$j$$$-th column for every $$$1\leq i \leq n$$$ and $$$1\leq j \leq m$$$. To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.More formally, let there be $$$k \ge 1$$$ black cells in the matrix with coordinates $$$(x_i,y_i)$$$ for every $$$1\leq i \leq k$$$. Lena should choose a cell $$$(a,b)$$$ that minimizes $$$$$$\max_{i=1}^{k}(|a-x_i|+|b-y_i|).$$$$$$As Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose?
Input Specification: There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$)Β β the number of test cases. This is followed by the test cases description. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2\leq n,m \leq 1000$$$) Β β the dimensions of the matrix. The following $$$n$$$ lines contain $$$m$$$ characters each, each character is either 'W' or 'B'. The $$$j$$$-th character in the $$$i$$$-th of these lines is 'W' if the cell $$$(i,j)$$$ is white, and 'B' if the cell $$$(i,j)$$$ is black. It is guaranteed that at least one black cell exists. It is guaranteed that the sum of $$$n\cdot m$$$ does not exceed $$$10^6$$$.
Output Specification: For each test case, output the optimal cell $$$(a,b)$$$ to choose. If multiple answers exist, output any.
Notes: NoteIn the first test case the two black cells have coordinates $$$(1,1)$$$ and $$$(3,2)$$$. The four optimal cells are $$$(1,2)$$$, $$$(2,1)$$$, $$$(2,2)$$$ and $$$(3,1)$$$. It can be shown that no other cell minimizes the maximum Manhattan distance to every black cell.In the second test case it is optimal to choose the black cell $$$(2,2)$$$ with maximum Manhattan distance being $$$2$$$.
Code:
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, m = map(int, input().split())
minr,minc,maxr,maxc=n,m,0,0
l1,l2,l3,l4=n+m,n+m,0,-n-m
b = []
for i in range(n):
r = input().rstrip()
#print('r',r)
#print(list(r))
#print(len(r))
for j, c in enumerate(r):
if c == 'B':
#print('i', i)
#print('j',j)
# minr = min(minr,i)
# maxr = max(maxr,i)
# minc = min(minc,j)
# maxc = max(maxc,j)
l1=min(l1,i+j)
l2=min(l2,i-j)
l3=max(l3,i+j)
l4=max(l4,i-j)
b.append((i,j))
#print('maxc',maxc)
#print('minc',minc)
#print('maxr',maxr)
#print('minr',minr)
# (l1+l3)//2 #r+c
# (l2+l4)//2 #r-c
r = (l1+l3+l2+l4)//4
c = (l1+l3-l2-l4)//4
bestr,bestc=r,c
#print(r,c)
best = float('inf')
for i in [-1,0,1]:
for j in [-1,0,1]:
if 0 <= i < n and 0 <= j < m:
madist = 0
cr, cc = r+i,c+j
for x,y in b:
# TODO: Your code here
#print(madist,cr,cc)
if madist < best:
best = madist
bestr,bestc=cr,cc
print(bestr+1,bestc+1)
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, m = map(int, input().split())
minr,minc,maxr,maxc=n,m,0,0
l1,l2,l3,l4=n+m,n+m,0,-n-m
b = []
for i in range(n):
r = input().rstrip()
#print('r',r)
#print(list(r))
#print(len(r))
for j, c in enumerate(r):
if c == 'B':
#print('i', i)
#print('j',j)
# minr = min(minr,i)
# maxr = max(maxr,i)
# minc = min(minc,j)
# maxc = max(maxc,j)
l1=min(l1,i+j)
l2=min(l2,i-j)
l3=max(l3,i+j)
l4=max(l4,i-j)
b.append((i,j))
#print('maxc',maxc)
#print('minc',minc)
#print('maxr',maxr)
#print('minr',minr)
# (l1+l3)//2 #r+c
# (l2+l4)//2 #r-c
r = (l1+l3+l2+l4)//4
c = (l1+l3-l2-l4)//4
bestr,bestc=r,c
#print(r,c)
best = float('inf')
for i in [-1,0,1]:
for j in [-1,0,1]:
if 0 <= i < n and 0 <= j < m:
madist = 0
cr, cc = r+i,c+j
for x,y in b:
{{completion}}
#print(madist,cr,cc)
if madist < best:
best = madist
bestr,bestc=cr,cc
print(bestr+1,bestc+1)
|
madist = max(madist,abs(cr-x)+abs(cc-y))
|
[{"input": "5\n3 2\nBW\nWW\nWB\n3 3\nWWB\nWBW\nBWW\n2 3\nBBB\nBBB\n5 5\nBWBWB\nWBWBW\nBWBWB\nWBWBW\nBWBWB\n9 9\nWWWWWWWWW\nWWWWWWWWW\nBWWWWWWWW\nWWWWWWWWW\nWWWWBWWWW\nWWWWWWWWW\nWWWWWWWWW\nWWWWWWWWW\nWWWWWWWWB", "output": ["2 1\n2 2\n1 2\n3 3\n6 5"]}]
|
block_completion_004377
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Lena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of $$$n$$$ rows and $$$m$$$ columns, and each cell is either black or white. The coordinates $$$(i,j)$$$ denote the cell which belongs to the $$$i$$$-th row and $$$j$$$-th column for every $$$1\leq i \leq n$$$ and $$$1\leq j \leq m$$$. To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.More formally, let there be $$$k \ge 1$$$ black cells in the matrix with coordinates $$$(x_i,y_i)$$$ for every $$$1\leq i \leq k$$$. Lena should choose a cell $$$(a,b)$$$ that minimizes $$$$$$\max_{i=1}^{k}(|a-x_i|+|b-y_i|).$$$$$$As Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose?
Input Specification: There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$)Β β the number of test cases. This is followed by the test cases description. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2\leq n,m \leq 1000$$$) Β β the dimensions of the matrix. The following $$$n$$$ lines contain $$$m$$$ characters each, each character is either 'W' or 'B'. The $$$j$$$-th character in the $$$i$$$-th of these lines is 'W' if the cell $$$(i,j)$$$ is white, and 'B' if the cell $$$(i,j)$$$ is black. It is guaranteed that at least one black cell exists. It is guaranteed that the sum of $$$n\cdot m$$$ does not exceed $$$10^6$$$.
Output Specification: For each test case, output the optimal cell $$$(a,b)$$$ to choose. If multiple answers exist, output any.
Notes: NoteIn the first test case the two black cells have coordinates $$$(1,1)$$$ and $$$(3,2)$$$. The four optimal cells are $$$(1,2)$$$, $$$(2,1)$$$, $$$(2,2)$$$ and $$$(3,1)$$$. It can be shown that no other cell minimizes the maximum Manhattan distance to every black cell.In the second test case it is optimal to choose the black cell $$$(2,2)$$$ with maximum Manhattan distance being $$$2$$$.
Code:
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, m = map(int, input().split())
minr,minc,maxr,maxc=n,m,0,0
l1,l2,l3,l4=n+m,n+m,0,-n-m
b = []
for i in range(n):
r = input().rstrip()
#print('r',r)
#print(list(r))
#print(len(r))
for j, c in enumerate(r):
if c == 'B':
#print('i', i)
#print('j',j)
# minr = min(minr,i)
# maxr = max(maxr,i)
# minc = min(minc,j)
# maxc = max(maxc,j)
l1=min(l1,i+j)
l2=min(l2,i-j)
l3=max(l3,i+j)
l4=max(l4,i-j)
b.append((i,j))
#print('maxc',maxc)
#print('minc',minc)
#print('maxr',maxr)
#print('minr',minr)
# (l1+l3)//2 #r+c
# (l2+l4)//2 #r-c
r = (l1+l3+l2+l4)//4
c = (l1+l3-l2-l4)//4
bestr,bestc=r,c
#print(r,c)
best = float('inf')
for i in [-1,0,1]:
for j in [-1,0,1]:
if 0 <= i < n and 0 <= j < m:
madist = 0
cr, cc = r+i,c+j
for x,y in b:
madist = max(madist,abs(cr-x)+abs(cc-y))
#print(madist,cr,cc)
if madist < best:
# TODO: Your code here
print(bestr+1,bestc+1)
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, m = map(int, input().split())
minr,minc,maxr,maxc=n,m,0,0
l1,l2,l3,l4=n+m,n+m,0,-n-m
b = []
for i in range(n):
r = input().rstrip()
#print('r',r)
#print(list(r))
#print(len(r))
for j, c in enumerate(r):
if c == 'B':
#print('i', i)
#print('j',j)
# minr = min(minr,i)
# maxr = max(maxr,i)
# minc = min(minc,j)
# maxc = max(maxc,j)
l1=min(l1,i+j)
l2=min(l2,i-j)
l3=max(l3,i+j)
l4=max(l4,i-j)
b.append((i,j))
#print('maxc',maxc)
#print('minc',minc)
#print('maxr',maxr)
#print('minr',minr)
# (l1+l3)//2 #r+c
# (l2+l4)//2 #r-c
r = (l1+l3+l2+l4)//4
c = (l1+l3-l2-l4)//4
bestr,bestc=r,c
#print(r,c)
best = float('inf')
for i in [-1,0,1]:
for j in [-1,0,1]:
if 0 <= i < n and 0 <= j < m:
madist = 0
cr, cc = r+i,c+j
for x,y in b:
madist = max(madist,abs(cr-x)+abs(cc-y))
#print(madist,cr,cc)
if madist < best:
{{completion}}
print(bestr+1,bestc+1)
|
best = madist
bestr,bestc=cr,cc
|
[{"input": "5\n3 2\nBW\nWW\nWB\n3 3\nWWB\nWBW\nBWW\n2 3\nBBB\nBBB\n5 5\nBWBWB\nWBWBW\nBWBWB\nWBWBW\nBWBWB\n9 9\nWWWWWWWWW\nWWWWWWWWW\nBWWWWWWWW\nWWWWWWWWW\nWWWWBWWWW\nWWWWWWWWW\nWWWWWWWWW\nWWWWWWWWW\nWWWWWWWWB", "output": ["2 1\n2 2\n1 2\n3 3\n6 5"]}]
|
block_completion_004378
|
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 collections import Counter
import heapq
for _ in range(int(input())):
_ = input()
l = input().split()
cnt = Counter(l)
x = list(cnt.values())
x.append(1)
hp = []
x.sort()
for i, n in enumerate(x):
if n-i-1 > 0:
# TODO: Your code here
cnt = 0
while hp and cnt + hp[0] < 0:
n = heapq.heappop(hp)
heapq.heappush(hp, n+1)
cnt += 1
print(len(x)+cnt)
|
from collections import Counter
import heapq
for _ in range(int(input())):
_ = input()
l = input().split()
cnt = Counter(l)
x = list(cnt.values())
x.append(1)
hp = []
x.sort()
for i, n in enumerate(x):
if n-i-1 > 0:
{{completion}}
cnt = 0
while hp and cnt + hp[0] < 0:
n = heapq.heappop(hp)
heapq.heappush(hp, n+1)
cnt += 1
print(len(x)+cnt)
|
heapq.heappush(hp, -(n-i-1))
|
[{"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"]}]
|
block_completion_004395
|
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:
t = int(input())
for i in range(t):
n = int(input())
p = [int(value) for value in input().split()]
tree = [0] * n
for i in range(len(p)):
tree[p[i] - 1] += 1
tree = sorted(tree)
resposta = 0
r = n
while resposta <= r:
s = 0
c = 1
m = (resposta + r) // 2
neg1 = -1
for i in range(n + neg1, neg1, neg1):
if tree[i] == 0:
# TODO: Your code here
aux = tree[i] + s - m
c += max(0, aux)
s += 1
if m - s >= c:
r = m - 1
else:
resposta = m + 1
print(resposta)
|
t = int(input())
for i in range(t):
n = int(input())
p = [int(value) for value in input().split()]
tree = [0] * n
for i in range(len(p)):
tree[p[i] - 1] += 1
tree = sorted(tree)
resposta = 0
r = n
while resposta <= r:
s = 0
c = 1
m = (resposta + r) // 2
neg1 = -1
for i in range(n + neg1, neg1, neg1):
if tree[i] == 0:
{{completion}}
aux = tree[i] + s - m
c += max(0, aux)
s += 1
if m - s >= c:
r = m - 1
else:
resposta = m + 1
print(resposta)
|
break
|
[{"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"]}]
|
block_completion_004396
|
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 to_spread and to_spread[0][0] <= turn:
# TODO: Your code here
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 to_spread and to_spread[0][0] <= turn:
{{completion}}
remain -= len(to_spread)
child_infected[isib] = True
heappush(to_spread, (len(children)+turn, isib))
remain -= 1
if remain <= 0:
break
print(turn+1)
|
heappop(to_spread)
|
[{"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"]}]
|
block_completion_004397
|
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 to_spread and to_spread[0][0] <= turn:
heappop(to_spread)
remain -= len(to_spread)
child_infected[isib] = True
heappush(to_spread, (len(children)+turn, isib))
remain -= 1
if remain <= 0:
# TODO: Your code here
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 to_spread and to_spread[0][0] <= turn:
heappop(to_spread)
remain -= len(to_spread)
child_infected[isib] = True
heappush(to_spread, (len(children)+turn, isib))
remain -= 1
if remain <= 0:
{{completion}}
print(turn+1)
|
break
|
[{"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"]}]
|
block_completion_004398
|
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 sys import stdin, stdout
from collections import defaultdict
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
parents = [int(x) for x in stdin.readline().split()]
counts = defaultdict(int)
counts[0] = 1
for i in parents:
counts[i] += 1
lives = [counts[i] for i in counts]
lives.sort(reverse=True)
for i in range(len(lives)):
lives[i] -= len(lives)-i
answer = len(lives)
while max(lives) > 0:
current_max = -1
max_index = -1
for i in range(len(lives)):
lives[i] -= 1
if lives[i] > current_max:
# TODO: Your code here
lives[max_index] -= 1
answer += 1
stdout.write("{}\n".format(answer))
|
from sys import stdin, stdout
from collections import defaultdict
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
parents = [int(x) for x in stdin.readline().split()]
counts = defaultdict(int)
counts[0] = 1
for i in parents:
counts[i] += 1
lives = [counts[i] for i in counts]
lives.sort(reverse=True)
for i in range(len(lives)):
lives[i] -= len(lives)-i
answer = len(lives)
while max(lives) > 0:
current_max = -1
max_index = -1
for i in range(len(lives)):
lives[i] -= 1
if lives[i] > current_max:
{{completion}}
lives[max_index] -= 1
answer += 1
stdout.write("{}\n".format(answer))
|
current_max = lives[i]
max_index = i
|
[{"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"]}]
|
block_completion_004399
|
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:
for _ in [0] * int(input()):
n = int(input())
a = list(map(int, input().split()))
c = [0] * n + [1]
for i in a:
c[i - 1] += 1
c = sorted(c, reverse=True)
ans = sum(i > 0 for i in c)
for i, j in enumerate(c):
if j > 0:
c[i] = i + j - ans
c = sorted([i for i in c if i > 0], reverse=True)
while c:
ans += 1
for i, j in enumerate(c):
if j > 0:
# TODO: Your code here
c = sorted([i for i in c if i > 0], reverse=True)
print(ans)
|
for _ in [0] * int(input()):
n = int(input())
a = list(map(int, input().split()))
c = [0] * n + [1]
for i in a:
c[i - 1] += 1
c = sorted(c, reverse=True)
ans = sum(i > 0 for i in c)
for i, j in enumerate(c):
if j > 0:
c[i] = i + j - ans
c = sorted([i for i in c if i > 0], reverse=True)
while c:
ans += 1
for i, j in enumerate(c):
if j > 0:
{{completion}}
c = sorted([i for i in c if i > 0], reverse=True)
print(ans)
|
c[i] = j - 1 - (i == 0)
|
[{"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"]}]
|
block_completion_004400
|
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:
inf=10**18
dxy=[(0,1), (1,0), (-1, 0), (0, -1)]
mod=10**9+7
MOD=998244353
from collections import Counter
def solve():
n = int(input())
p = [int(i)-1 for i in input().split()]
c = Counter(p)
ans = len(c.values())+1
adi = []
for i, n in enumerate(sorted(c.values(), reverse=True)):
if n+i-ans>0:
adi.append(n+i-ans)
if adi:
adi.sort(reverse=True)
cnt = 0
#bi search
r = max(adi)+1
l = 0
def is_ok(x):
d = 0
for i in adi:
d += max(0, i-x)
return d-x<=0
while r-l>1:
mid = (r+l)//2
if is_ok(mid):r = mid
else: # TODO: Your code here
ans += r
return ans
def main():
T = int(input())
for _ in range(T):
print(solve())
main()
|
inf=10**18
dxy=[(0,1), (1,0), (-1, 0), (0, -1)]
mod=10**9+7
MOD=998244353
from collections import Counter
def solve():
n = int(input())
p = [int(i)-1 for i in input().split()]
c = Counter(p)
ans = len(c.values())+1
adi = []
for i, n in enumerate(sorted(c.values(), reverse=True)):
if n+i-ans>0:
adi.append(n+i-ans)
if adi:
adi.sort(reverse=True)
cnt = 0
#bi search
r = max(adi)+1
l = 0
def is_ok(x):
d = 0
for i in adi:
d += max(0, i-x)
return d-x<=0
while r-l>1:
mid = (r+l)//2
if is_ok(mid):r = mid
else: {{completion}}
ans += r
return ans
def main():
T = int(input())
for _ in range(T):
print(solve())
main()
|
l = mid
|
[{"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"]}]
|
block_completion_004401
|
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 heappop, heappush
t = int(input())
const = 1 << 18
for T in range(t):
n = int(input())
arr = [int(x) for x in input().split(" ")]
things = {0: const}
for x in range(len(arr)):
if arr[x] in things:
things[arr[x]] += 1
else:
things[arr[x]] = const
laze = []
for x in things:
heappush(laze, -things[x])
time = 0
while len(laze) > 0:
f = -laze[0]
if f <= time:
heappop(laze)
continue
elif f >= const:
f -= const
f += time + 1
heappop(laze)
if f > time:
# TODO: Your code here
else:
f -= 1
heappop(laze)
if f > time:
heappush(laze, -f)
time += 1
print(time)
|
from heapq import heappop, heappush
t = int(input())
const = 1 << 18
for T in range(t):
n = int(input())
arr = [int(x) for x in input().split(" ")]
things = {0: const}
for x in range(len(arr)):
if arr[x] in things:
things[arr[x]] += 1
else:
things[arr[x]] = const
laze = []
for x in things:
heappush(laze, -things[x])
time = 0
while len(laze) > 0:
f = -laze[0]
if f <= time:
heappop(laze)
continue
elif f >= const:
f -= const
f += time + 1
heappop(laze)
if f > time:
{{completion}}
else:
f -= 1
heappop(laze)
if f > time:
heappush(laze, -f)
time += 1
print(time)
|
heappush(laze, -f)
|
[{"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"]}]
|
block_completion_004402
|
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 heappop, heappush
t = int(input())
const = 1 << 18
for T in range(t):
n = int(input())
arr = [int(x) for x in input().split(" ")]
things = {0: const}
for x in range(len(arr)):
if arr[x] in things:
things[arr[x]] += 1
else:
things[arr[x]] = const
laze = []
for x in things:
heappush(laze, -things[x])
time = 0
while len(laze) > 0:
f = -laze[0]
if f <= time:
heappop(laze)
continue
elif f >= const:
f -= const
f += time + 1
heappop(laze)
if f > time:
heappush(laze, -f)
else:
f -= 1
heappop(laze)
if f > time:
# TODO: Your code here
time += 1
print(time)
|
from heapq import heappop, heappush
t = int(input())
const = 1 << 18
for T in range(t):
n = int(input())
arr = [int(x) for x in input().split(" ")]
things = {0: const}
for x in range(len(arr)):
if arr[x] in things:
things[arr[x]] += 1
else:
things[arr[x]] = const
laze = []
for x in things:
heappush(laze, -things[x])
time = 0
while len(laze) > 0:
f = -laze[0]
if f <= time:
heappop(laze)
continue
elif f >= const:
f -= const
f += time + 1
heappop(laze)
if f > time:
heappush(laze, -f)
else:
f -= 1
heappop(laze)
if f > time:
{{completion}}
time += 1
print(time)
|
heappush(laze, -f)
|
[{"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"]}]
|
block_completion_004403
|
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 collections import defaultdict
counter = defaultdict(int)
def solve(a):
for ai in a:
counter[ai] += 1
count = list(counter.values())
num_level = len(count)
count.sort()
for i in range(num_level):
count[i] = max(count[i] - i - 2, 0)
L = 0; R = max(count)
if R == 0:
return num_level + 1
def check(k):
b = count.copy()
for i in range(len(b)):
b[i] = max(b[i] - k, 0)
if sum(b) <= k:
return True
return False
while R - L > 1:
mid = (R + L) // 2
if(check(mid)):
R = mid
else:
# TODO: Your code here
return num_level + 1 + R
for a in [*open(0)][2::2]:
counter.clear()
res = solve(a.split())
print(res)
|
from collections import defaultdict
counter = defaultdict(int)
def solve(a):
for ai in a:
counter[ai] += 1
count = list(counter.values())
num_level = len(count)
count.sort()
for i in range(num_level):
count[i] = max(count[i] - i - 2, 0)
L = 0; R = max(count)
if R == 0:
return num_level + 1
def check(k):
b = count.copy()
for i in range(len(b)):
b[i] = max(b[i] - k, 0)
if sum(b) <= k:
return True
return False
while R - L > 1:
mid = (R + L) // 2
if(check(mid)):
R = mid
else:
{{completion}}
return num_level + 1 + R
for a in [*open(0)][2::2]:
counter.clear()
res = solve(a.split())
print(res)
|
L = mid
|
[{"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"]}]
|
block_completion_004404
|
block
|
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: 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*
for a in[*open(0)][2::2]:
n=len(a:=a.split());m=max(Counter(a).values());r=0
while m<n:# TODO: Your code here
print(r)
|
from collections import*
for a in[*open(0)][2::2]:
n=len(a:=a.split());m=max(Counter(a).values());r=0
while m<n:{{completion}}
print(r)
|
r+=min(m,n-m)+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_004420
|
block
|
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:
import math
for t in range(int(input())):
n=int(input())
L=input().split()
count={}
for i in L:
try:
count[i]+=1
except:
# TODO: Your code here
m=max(list(count.values()))
print(int(n-m + math.ceil(math.log(n/m,2))))
|
import math
for t in range(int(input())):
n=int(input())
L=input().split()
count={}
for i in L:
try:
count[i]+=1
except:
{{completion}}
m=max(list(count.values()))
print(int(n-m + math.ceil(math.log(n/m,2))))
|
count[i]=1
|
[{"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_004421
|
block
|
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:
if True:
from collections import Counter
t = int(input())
for _ in range(t):
# TODO: Your code here
|
if True:
from collections import Counter
t = int(input())
for _ in range(t):
{{completion}}
|
n = int(input())
d = Counter(input().split()).most_common(1)[0][1]
print([i for i in range(18) if (2**i)*d >= n][0]+n-d)
|
[{"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_004422
|
block
|
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 sys import stdin
t = int(stdin.readline())
while t>0:
t -= 1
n = int(stdin.readline())
a = sorted(list(map(int,stdin.readline().split())))
M = 1
temp = 1
for i in range(1,n):
if a[i]>a[i-1]:
temp = 1
else:
# TODO: Your code here
M = max(M,temp)
ind = 0
temp = M
while temp<n:
ind += 1
temp *= 2
print(n-M+ind)
|
from sys import stdin
t = int(stdin.readline())
while t>0:
t -= 1
n = int(stdin.readline())
a = sorted(list(map(int,stdin.readline().split())))
M = 1
temp = 1
for i in range(1,n):
if a[i]>a[i-1]:
temp = 1
else:
{{completion}}
M = max(M,temp)
ind = 0
temp = M
while temp<n:
ind += 1
temp *= 2
print(n-M+ind)
|
temp += 1
|
[{"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_004423
|
block
|
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:
for i in range(int(input())):
n=int(input())
a=input().split()
from collections import Counter
e,bb=Counter(a).most_common(1)[0]
c=n-bb
while bb<n:
# TODO: Your code here
print(c)
|
for i in range(int(input())):
n=int(input())
a=input().split()
from collections import Counter
e,bb=Counter(a).most_common(1)[0]
c=n-bb
while bb<n:
{{completion}}
print(c)
|
c+=1
bb*=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_004424
|
block
|
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 li in[*open(0)][2::2]:
n=len(li:=li.split());
m = max(Counter(li).values())
ans =n-m
while(m<n):
# TODO: Your code here
print(ans)
|
from collections import Counter
for li in[*open(0)][2::2]:
n=len(li:=li.split());
m = max(Counter(li).values())
ans =n-m
while(m<n):
{{completion}}
print(ans)
|
ans+=1
m=2*m
|
[{"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_004425
|
block
|
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
def solve():
n = int(input())
freq = max(Counter(input().split()).values())
left = n - freq
ans=0
while(left):
ans += 1+min(left,freq)
left = left - min(left,freq)
freq=2*freq
print(ans)
while(True):
try:
test = int(input())
except EOFError:
# TODO: Your code here
for i in range (test):
solve()
|
from collections import Counter
def solve():
n = int(input())
freq = max(Counter(input().split()).values())
left = n - freq
ans=0
while(left):
ans += 1+min(left,freq)
left = left - min(left,freq)
freq=2*freq
print(ans)
while(True):
try:
test = int(input())
except EOFError:
{{completion}}
for i in range (test):
solve()
|
break
|
[{"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_004426
|
block
|
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 sys import stdin, stdout
from collections import Counter
for _ in range(int(stdin.readline().strip())):
n = int(stdin.readline().strip())
b = a = max(Counter(stdin.readline().split()).items(), key = lambda x:x[1])[1]
ans = n - a
while a < n:
# TODO: Your code here
stdout.write(f"{str(ans)}\n")
|
from sys import stdin, stdout
from collections import Counter
for _ in range(int(stdin.readline().strip())):
n = int(stdin.readline().strip())
b = a = max(Counter(stdin.readline().split()).items(), key = lambda x:x[1])[1]
ans = n - a
while a < n:
{{completion}}
stdout.write(f"{str(ans)}\n")
|
a = a + a
ans += 1
|
[{"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_004427
|
block
|
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:
N=int(input())
for _ in range(N):
n = int(input())
list_num = input().split(' ')
d = dict()
for num in list_num:
if num in d:
d[num] = d[num] + 1
else:
# TODO: Your code here
max_num = max(d.values())
now = max_num
ans = 0
copy = 0
while now < n:
if copy > 0:
ans += 1
copy -= 1
now += 1
else:
ans += 1
copy = now
print (ans)
|
N=int(input())
for _ in range(N):
n = int(input())
list_num = input().split(' ')
d = dict()
for num in list_num:
if num in d:
d[num] = d[num] + 1
else:
{{completion}}
max_num = max(d.values())
now = max_num
ans = 0
copy = 0
while now < n:
if copy > 0:
ans += 1
copy -= 1
now += 1
else:
ans += 1
copy = now
print (ans)
|
d[num] = 1
|
[{"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_004428
|
block
|
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:
N=int(input())
for _ in range(N):
n = int(input())
list_num = input().split(' ')
d = dict()
for num in list_num:
if num in d:
d[num] = d[num] + 1
else:
d[num] = 1
max_num = max(d.values())
now = max_num
ans = 0
copy = 0
while now < n:
if copy > 0:
ans += 1
copy -= 1
now += 1
else:
# TODO: Your code here
print (ans)
|
N=int(input())
for _ in range(N):
n = int(input())
list_num = input().split(' ')
d = dict()
for num in list_num:
if num in d:
d[num] = d[num] + 1
else:
d[num] = 1
max_num = max(d.values())
now = max_num
ans = 0
copy = 0
while now < n:
if copy > 0:
ans += 1
copy -= 1
now += 1
else:
{{completion}}
print (ans)
|
ans += 1
copy = now
|
[{"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_004429
|
block
|
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:
t=int(input())
for i in range (t):
n = int(input())
m=n//4
if n%4==0:
print(m,m,m,m,end=' ')
elif n%4==1:
# TODO: Your code here
elif n%4==2:
print(2*m-1,2*m+1,1,1,end=' ')
else:
print(2,4*m-2,2,1,end=' ')
print(sep='')
|
t=int(input())
for i in range (t):
n = int(input())
m=n//4
if n%4==0:
print(m,m,m,m,end=' ')
elif n%4==1:
{{completion}}
elif n%4==2:
print(2*m-1,2*m+1,1,1,end=' ')
else:
print(2,4*m-2,2,1,end=' ')
print(sep='')
|
print(m,2*m,m,1,end=' ')
|
[{"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_004455
|
block
|
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:
t=int(input())
for i in range (t):
n = int(input())
m=n//4
if n%4==0:
print(m,m,m,m,end=' ')
elif n%4==1:
print(m,2*m,m,1,end=' ')
elif n%4==2:
# TODO: Your code here
else:
print(2,4*m-2,2,1,end=' ')
print(sep='')
|
t=int(input())
for i in range (t):
n = int(input())
m=n//4
if n%4==0:
print(m,m,m,m,end=' ')
elif n%4==1:
print(m,2*m,m,1,end=' ')
elif n%4==2:
{{completion}}
else:
print(2,4*m-2,2,1,end=' ')
print(sep='')
|
print(2*m-1,2*m+1,1,1,end=' ')
|
[{"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_004456
|
block
|
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())):
n = int(input())
if n == 4:
a = b = c = d = 1
elif n == 5:
# TODO: Your code here
elif n == 6:
a = c = d = 1
b = 3
elif n%4 == 0:
c = d = b = 2
a = n-6
elif n%4 == 1:
d = 1
c = 2
a = 2
b = n-5
elif n%4 == 2:
d = 1
c = 1
a = (n-2)//2 - 1
b = (n-2)//2 + 1
else:
d = 1
c = 2
b = 2
a = n-5
print(a, b, c, d)
|
for _ in range(int(input())):
n = int(input())
if n == 4:
a = b = c = d = 1
elif n == 5:
{{completion}}
elif n == 6:
a = c = d = 1
b = 3
elif n%4 == 0:
c = d = b = 2
a = n-6
elif n%4 == 1:
d = 1
c = 2
a = 2
b = n-5
elif n%4 == 2:
d = 1
c = 1
a = (n-2)//2 - 1
b = (n-2)//2 + 1
else:
d = 1
c = 2
b = 2
a = n-5
print(a, b, c, d)
|
a = c = d = 1
b = 2
|
[{"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_004457
|
block
|
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())):
n = int(input())
if n == 4:
a = b = c = d = 1
elif n == 5:
a = c = d = 1
b = 2
elif n == 6:
# TODO: Your code here
elif n%4 == 0:
c = d = b = 2
a = n-6
elif n%4 == 1:
d = 1
c = 2
a = 2
b = n-5
elif n%4 == 2:
d = 1
c = 1
a = (n-2)//2 - 1
b = (n-2)//2 + 1
else:
d = 1
c = 2
b = 2
a = n-5
print(a, b, c, d)
|
for _ in range(int(input())):
n = int(input())
if n == 4:
a = b = c = d = 1
elif n == 5:
a = c = d = 1
b = 2
elif n == 6:
{{completion}}
elif n%4 == 0:
c = d = b = 2
a = n-6
elif n%4 == 1:
d = 1
c = 2
a = 2
b = n-5
elif n%4 == 2:
d = 1
c = 1
a = (n-2)//2 - 1
b = (n-2)//2 + 1
else:
d = 1
c = 2
b = 2
a = n-5
print(a, b, c, d)
|
a = c = d = 1
b = 3
|
[{"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_004458
|
block
|
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:
t = int(input())
for _ in range(t):
n = int(input())
ans = []
if n == 5:
ans = [1, 2, 1, 1]
elif n % 4 == 0:
# TODO: Your code here
elif n % 2 == 0:
ans = [(n - 2) // 2 - 1, (n - 2) // 2 + 1, 1, 1]
else:
a, c, d = 2, 2, 1
b = n - a - c - d
ans = [a, b, c, d]
print(' '.join([str(a) for a in ans]))
|
t = int(input())
for _ in range(t):
n = int(input())
ans = []
if n == 5:
ans = [1, 2, 1, 1]
elif n % 4 == 0:
{{completion}}
elif n % 2 == 0:
ans = [(n - 2) // 2 - 1, (n - 2) // 2 + 1, 1, 1]
else:
a, c, d = 2, 2, 1
b = n - a - c - d
ans = [a, b, c, d]
print(' '.join([str(a) for a in ans]))
|
ans = [n // 4] * 4
|
[{"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_004459
|
block
|
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:
t = int(input())
for _ in range(t):
n = int(input())
ans = []
if n == 5:
ans = [1, 2, 1, 1]
elif n % 4 == 0:
ans = [n // 4] * 4
elif n % 2 == 0:
# TODO: Your code here
else:
a, c, d = 2, 2, 1
b = n - a - c - d
ans = [a, b, c, d]
print(' '.join([str(a) for a in ans]))
|
t = int(input())
for _ in range(t):
n = int(input())
ans = []
if n == 5:
ans = [1, 2, 1, 1]
elif n % 4 == 0:
ans = [n // 4] * 4
elif n % 2 == 0:
{{completion}}
else:
a, c, d = 2, 2, 1
b = n - a - c - d
ans = [a, b, c, d]
print(' '.join([str(a) for a in ans]))
|
ans = [(n - 2) // 2 - 1, (n - 2) // 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_004460
|
block
|
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 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:
a1=a-2
print(a1//2,a1//2+1,1,1)
elif a1%4==0:
# TODO: Your code here
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:
a1=a-2
print(a1//2,a1//2+1,1,1)
elif a1%4==0:
{{completion}}
else:
a1=a-2
print(a1//2-1,a1//2+1,1,1)
|
print(a1//4,a1//2,a1//4,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_004462
|
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: 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:
import sys
n = int(input())
a = [int(x)-1 for x in sys.stdin.readline().split()]
depth = [1]*n
best = [0]*n
for i in range(n-1, -1, -1):
best[i] = max(best[i], depth[i])
if i != 0:
# TODO: Your code here
print(best[0])
|
import sys
n = int(input())
a = [int(x)-1 for x in sys.stdin.readline().split()]
depth = [1]*n
best = [0]*n
for i in range(n-1, -1, -1):
best[i] = max(best[i], depth[i])
if i != 0:
{{completion}}
print(best[0])
|
parent = a[i-1]
depth[parent] = max(depth[parent], 1 + depth[i])
best[parent] += best[i]
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004724
|
block
|
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:
mod = 998244353
def main():
import sys
input = sys.stdin.readline
N = int(input())
P = [0, 0] + list(map(int, input().split()))
child = [[] for _ in range(N + 1)]
for v in range(2, N+1):
p = P[v]
child[p].append(v)
dp = [0] * (N + 1)
dp2 = [0] * (N + 1)
for v in range(N, 0, -1):
if not child[v]:
dp2[v] = 1
dp[v] = 1
else:
S = 0
D = 0
for c in child[v]:
# TODO: Your code here
dp2[v] = D + 1
dp[v] = max(S, D + 1)
print(dp[1])
#print(dp, dp2)
if __name__ == '__main__':
main()
|
mod = 998244353
def main():
import sys
input = sys.stdin.readline
N = int(input())
P = [0, 0] + list(map(int, input().split()))
child = [[] for _ in range(N + 1)]
for v in range(2, N+1):
p = P[v]
child[p].append(v)
dp = [0] * (N + 1)
dp2 = [0] * (N + 1)
for v in range(N, 0, -1):
if not child[v]:
dp2[v] = 1
dp[v] = 1
else:
S = 0
D = 0
for c in child[v]:
{{completion}}
dp2[v] = D + 1
dp[v] = max(S, D + 1)
print(dp[1])
#print(dp, dp2)
if __name__ == '__main__':
main()
|
S += dp[c]
D = max(D, dp2[c])
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004725
|
block
|
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=[-1]+[int(o)-1 for o in input().split()]
f=[0]*n
dp=[0]*n
for i in range(n-1,0,-1):
# TODO: Your code here
for i in range(n-1,0,-1):
dp[i]=max(dp[i],f[i]+1)
dp[a[i]]+=dp[i]
print(max(dp[0],f[0]+1))
|
n=int(input())
a=[-1]+[int(o)-1 for o in input().split()]
f=[0]*n
dp=[0]*n
for i in range(n-1,0,-1):
{{completion}}
for i in range(n-1,0,-1):
dp[i]=max(dp[i],f[i]+1)
dp[a[i]]+=dp[i]
print(max(dp[0],f[0]+1))
|
f[a[i]]=max(f[i]+1,f[a[i]])
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004726
|
block
|
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=[-1]+[int(o)-1 for o in input().split()]
f=[0]*n
dp=[0]*n
for i in range(n-1,0,-1):
f[a[i]]=max(f[i]+1,f[a[i]])
for i in range(n-1,0,-1):
# TODO: Your code here
print(max(dp[0],f[0]+1))
|
n=int(input())
a=[-1]+[int(o)-1 for o in input().split()]
f=[0]*n
dp=[0]*n
for i in range(n-1,0,-1):
f[a[i]]=max(f[i]+1,f[a[i]])
for i in range(n-1,0,-1):
{{completion}}
print(max(dp[0],f[0]+1))
|
dp[i]=max(dp[i],f[i]+1)
dp[a[i]]+=dp[i]
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004727
|
block
|
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:
I,G=input,range;n=int(I());p=[-1,0]+[*map(int,I().split())];h=[1]*(n+1);F=[0]*(n+1)
for i in G(n,1,-1):# TODO: Your code here
for i in G(n,0,-1):F[i]=max(F[i],h[i]);F[p[i]]+=F[i]
print(F[1])
|
I,G=input,range;n=int(I());p=[-1,0]+[*map(int,I().split())];h=[1]*(n+1);F=[0]*(n+1)
for i in G(n,1,-1):{{completion}}
for i in G(n,0,-1):F[i]=max(F[i],h[i]);F[p[i]]+=F[i]
print(F[1])
|
h[p[i]]=max(h[i]+1,h[p[i]])
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004728
|
block
|
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:
I,G=input,range;n=int(I());p=[-1,0]+[*map(int,I().split())];h=[1]*(n+1);F=[0]*(n+1)
for i in G(n,1,-1):h[p[i]]=max(h[i]+1,h[p[i]])
for i in G(n,0,-1):# TODO: Your code here
print(F[1])
|
I,G=input,range;n=int(I());p=[-1,0]+[*map(int,I().split())];h=[1]*(n+1);F=[0]*(n+1)
for i in G(n,1,-1):h[p[i]]=max(h[i]+1,h[p[i]])
for i in G(n,0,-1):{{completion}}
print(F[1])
|
F[i]=max(F[i],h[i]);F[p[i]]+=F[i]
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004729
|
block
|
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 v in edge[r]:
# TODO: Your code here
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 v in edge[r]:
{{completion}}
print(max(dp[0]))
|
k = max(dp[v])
dp[r][1] += k
dp[r][0] = max(dp[r][0],dp[v][0]+1)
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004730
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek is given an array $$$a$$$ of $$$n$$$ integers. For each $$$i$$$ ($$$1 \leq i \leq n$$$), Pak Chanek will write the one-element set $$$\{a_i\}$$$ on a whiteboard.After that, in one operation, Pak Chanek may do the following: Choose two different sets $$$S$$$ and $$$T$$$ on the whiteboard such that $$$S \cap T = \varnothing$$$ ($$$S$$$ and $$$T$$$ do not have any common elements). Erase $$$S$$$ and $$$T$$$ from the whiteboard and write $$$S \cup T$$$ (the union of $$$S$$$ and $$$T$$$) onto the whiteboard. After performing zero or more operations, Pak Chanek will construct a multiset $$$M$$$ containing the sizes of all sets written on the whiteboard. In other words, each element in $$$M$$$ corresponds to the size of a set after the operations.How many distinct$$$^\dagger$$$ multisets $$$M$$$ can be created by this process? Since the answer may be large, output it modulo $$$998\,244\,353$$$.$$$^\dagger$$$ Multisets $$$B$$$ and $$$C$$$ are different if and only if there exists a value $$$k$$$ such that the number of elements with value $$$k$$$ in $$$B$$$ is different than the number of elements with value $$$k$$$ in $$$C$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
Output Specification: Output the number of distinct multisets $$$M$$$ modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, the possible multisets $$$M$$$ are $$$\{1,1,1,1,1,1\}$$$, $$$\{1,1,1,1,2\}$$$, $$$\{1,1,1,3\}$$$, $$$\{1,1,2,2\}$$$, $$$\{1,1,4\}$$$, $$$\{1,2,3\}$$$, and $$$\{2,2,2\}$$$.As an example, let's consider a possible sequence of operations. In the beginning, the sets are $$$\{1\}$$$, $$$\{1\}$$$, $$$\{2\}$$$, $$$\{1\}$$$, $$$\{4\}$$$, and $$$\{3\}$$$. Do an operation on sets $$$\{1\}$$$ and $$$\{3\}$$$. Now, the sets are $$$\{1\}$$$, $$$\{1\}$$$, $$$\{2\}$$$, $$$\{4\}$$$, and $$$\{1,3\}$$$. Do an operation on sets $$$\{2\}$$$ and $$$\{4\}$$$. Now, the sets are $$$\{1\}$$$, $$$\{1\}$$$, $$$\{1,3\}$$$, and $$$\{2,4\}$$$. Do an operation on sets $$$\{1,3\}$$$ and $$$\{2,4\}$$$. Now, the sets are $$$\{1\}$$$, $$$\{1\}$$$, and $$$\{1,2,3,4\}$$$. The multiset $$$M$$$ that is constructed is $$$\{1,1,4\}$$$.
Code:
from sys import stdin, stdout
from collections import defaultdict
N = 998244353
n = int(stdin.readline())
a = [int(x)-1 for x in stdin.readline().split()]
count = [0]*n
row_values = [0]*n
for i in range(n):
row_values[count[a[i]]] += 1
count[a[i]] += 1
row_values_pref = [row_values[0]]
for i in range(1,n):
row_values_pref.append(row_values_pref[-1]+row_values[i])
dp = [[0]*(n+1) for bar in range(n+1)]
for i in range(1,row_values[0]+1):
dp[i][i] = 1
for i in range(1,n):
for total in range(n-1,0,-1):
current = 0
for last in range(total//i, 0, -1):
current += dp[total][last]
current %= N
dp[total][last] = 0
if last <= min(row_values_pref[i]-total, n-total):
# TODO: Your code here
answer = 0
for i in range(1,n+1):
answer += dp[n][i]
answer %= N
stdout.write(str(answer)+'\n')
|
from sys import stdin, stdout
from collections import defaultdict
N = 998244353
n = int(stdin.readline())
a = [int(x)-1 for x in stdin.readline().split()]
count = [0]*n
row_values = [0]*n
for i in range(n):
row_values[count[a[i]]] += 1
count[a[i]] += 1
row_values_pref = [row_values[0]]
for i in range(1,n):
row_values_pref.append(row_values_pref[-1]+row_values[i])
dp = [[0]*(n+1) for bar in range(n+1)]
for i in range(1,row_values[0]+1):
dp[i][i] = 1
for i in range(1,n):
for total in range(n-1,0,-1):
current = 0
for last in range(total//i, 0, -1):
current += dp[total][last]
current %= N
dp[total][last] = 0
if last <= min(row_values_pref[i]-total, n-total):
{{completion}}
answer = 0
for i in range(1,n+1):
answer += dp[n][i]
answer %= N
stdout.write(str(answer)+'\n')
|
dp[total+last][last] += current
dp[total+last][last] %= N
|
[{"input": "6\n1 1 2 1 4 3", "output": ["7"]}, {"input": "7\n3 5 4 3 7 4 5", "output": ["11"]}]
|
block_completion_004745
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek is given an array $$$a$$$ of $$$n$$$ integers. For each $$$i$$$ ($$$1 \leq i \leq n$$$), Pak Chanek will write the one-element set $$$\{a_i\}$$$ on a whiteboard.After that, in one operation, Pak Chanek may do the following: Choose two different sets $$$S$$$ and $$$T$$$ on the whiteboard such that $$$S \cap T = \varnothing$$$ ($$$S$$$ and $$$T$$$ do not have any common elements). Erase $$$S$$$ and $$$T$$$ from the whiteboard and write $$$S \cup T$$$ (the union of $$$S$$$ and $$$T$$$) onto the whiteboard. After performing zero or more operations, Pak Chanek will construct a multiset $$$M$$$ containing the sizes of all sets written on the whiteboard. In other words, each element in $$$M$$$ corresponds to the size of a set after the operations.How many distinct$$$^\dagger$$$ multisets $$$M$$$ can be created by this process? Since the answer may be large, output it modulo $$$998\,244\,353$$$.$$$^\dagger$$$ Multisets $$$B$$$ and $$$C$$$ are different if and only if there exists a value $$$k$$$ such that the number of elements with value $$$k$$$ in $$$B$$$ is different than the number of elements with value $$$k$$$ in $$$C$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
Output Specification: Output the number of distinct multisets $$$M$$$ modulo $$$998\,244\,353$$$.
Notes: NoteIn the first example, the possible multisets $$$M$$$ are $$$\{1,1,1,1,1,1\}$$$, $$$\{1,1,1,1,2\}$$$, $$$\{1,1,1,3\}$$$, $$$\{1,1,2,2\}$$$, $$$\{1,1,4\}$$$, $$$\{1,2,3\}$$$, and $$$\{2,2,2\}$$$.As an example, let's consider a possible sequence of operations. In the beginning, the sets are $$$\{1\}$$$, $$$\{1\}$$$, $$$\{2\}$$$, $$$\{1\}$$$, $$$\{4\}$$$, and $$$\{3\}$$$. Do an operation on sets $$$\{1\}$$$ and $$$\{3\}$$$. Now, the sets are $$$\{1\}$$$, $$$\{1\}$$$, $$$\{2\}$$$, $$$\{4\}$$$, and $$$\{1,3\}$$$. Do an operation on sets $$$\{2\}$$$ and $$$\{4\}$$$. Now, the sets are $$$\{1\}$$$, $$$\{1\}$$$, $$$\{1,3\}$$$, and $$$\{2,4\}$$$. Do an operation on sets $$$\{1,3\}$$$ and $$$\{2,4\}$$$. Now, the sets are $$$\{1\}$$$, $$$\{1\}$$$, and $$$\{1,2,3,4\}$$$. The multiset $$$M$$$ that is constructed is $$$\{1,1,4\}$$$.
Code:
import sys
input = sys.stdin.readline
inf = float('inf')
def getInt():
return int(input())
def getStr():
return input().strip()
def getList(split=True):
s = getStr()
if split:
s = s.split()
return map(int, s)
# t = getInt()
t = 1
M = 998244353
def solve():
n = getInt()
a = list(getList())
cnt = [0] * n
for i in a:
cnt[i-1] += 1
lim = [0] * (n+1)
col = 0 # the number of remaining columns, initial col = number of distinct element
f = [0] * (n+1) # frequent of the height of columns
for i, j in enumerate(cnt):
col += j > 0
f[j] += 1
for i in range(1, n+1):
lim[i] = lim[i-1] + col
col -= f[i]
dp = [[0] * (n+1) for _ in range(n+1)]
dp[0][0] = 1
for x in range(n, 0, -1):
# dp[i][j] used elements + size of multiset
for j in range(n):
# transition
# x * j <= n
# i+x <= lim[j+1]
if j * x > n:
break
for i in range(n-x+1):
if i + x <= lim[j+1]:
# TODO: Your code here
print(sum(dp[n]) % M)
for _ in range(t):
solve()
|
import sys
input = sys.stdin.readline
inf = float('inf')
def getInt():
return int(input())
def getStr():
return input().strip()
def getList(split=True):
s = getStr()
if split:
s = s.split()
return map(int, s)
# t = getInt()
t = 1
M = 998244353
def solve():
n = getInt()
a = list(getList())
cnt = [0] * n
for i in a:
cnt[i-1] += 1
lim = [0] * (n+1)
col = 0 # the number of remaining columns, initial col = number of distinct element
f = [0] * (n+1) # frequent of the height of columns
for i, j in enumerate(cnt):
col += j > 0
f[j] += 1
for i in range(1, n+1):
lim[i] = lim[i-1] + col
col -= f[i]
dp = [[0] * (n+1) for _ in range(n+1)]
dp[0][0] = 1
for x in range(n, 0, -1):
# dp[i][j] used elements + size of multiset
for j in range(n):
# transition
# x * j <= n
# i+x <= lim[j+1]
if j * x > n:
break
for i in range(n-x+1):
if i + x <= lim[j+1]:
{{completion}}
print(sum(dp[n]) % M)
for _ in range(t):
solve()
|
dp[i+x][j+1] += dp[i][j]
dp[i+x][j+1] %= M
|
[{"input": "6\n1 1 2 1 4 3", "output": ["7"]}, {"input": "7\n3 5 4 3 7 4 5", "output": ["11"]}]
|
block_completion_004746
|
block
|
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:
g=10**9+7
v=[1]+[0]*40001
for i in range(1,40001):
if str(i)==str(i)[::-1]:
for j in range(i,40001):# TODO: Your code here
for n in[*open(0)][1:]:print(v[int(n)]%g)
|
g=10**9+7
v=[1]+[0]*40001
for i in range(1,40001):
if str(i)==str(i)[::-1]:
for j in range(i,40001):{{completion}}
for n in[*open(0)][1:]:print(v[int(n)]%g)
|
v[j]=v[j]%g+v[j-i]
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004780
|
block
|
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:
p=[]
for i in range(1,40004):
s=str(i)
if s==s[::-1]:
p+=[i]
n=40004
d=[0]*(n+1)
for pj in p:
d[0] = 1
for i in range(1,n+1):
if pj<=i:
# TODO: Your code here
d[i]=d[i]%int(1e9+7)
for _ in range(int(input())):
print(d[int(input())])
|
p=[]
for i in range(1,40004):
s=str(i)
if s==s[::-1]:
p+=[i]
n=40004
d=[0]*(n+1)
for pj in p:
d[0] = 1
for i in range(1,n+1):
if pj<=i:
{{completion}}
d[i]=d[i]%int(1e9+7)
for _ in range(int(input())):
print(d[int(input())])
|
d[i]+=d[i-pj]
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004781
|
block
|
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:
n = int(input())
def getList():
return map(int, input().split())
def getInt():
return int(input())
N = 4 * 10 ** 4 + 10
M = 10 ** 9 + 7
dp = [0] * N
for i in range(1, N):
if str(i) == str(i)[::-1]:
dp[i] += 1
for j in range(i, N):
# TODO: Your code here
def solve():
n = getInt()
print(dp[n])
for _ in range(n):
solve()
|
n = int(input())
def getList():
return map(int, input().split())
def getInt():
return int(input())
N = 4 * 10 ** 4 + 10
M = 10 ** 9 + 7
dp = [0] * N
for i in range(1, N):
if str(i) == str(i)[::-1]:
dp[i] += 1
for j in range(i, N):
{{completion}}
def solve():
n = getInt()
print(dp[n])
for _ in range(n):
solve()
|
dp[j] += dp[j-i]
dp[j] %= M
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004782
|
block
|
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:
from sys import stdin,stdout
input = lambda : stdin.readline().rstrip()
print =lambda x : stdout.write(str(x))
dp = [0 for _ in range(40002)]
dp[0] = 1
for i in range(1, 40001):
if str(i) == str(i)[::-1]:
for j in range(i, 40001):
# TODO: Your code here
for _ in range(int(input())):
print(f"{dp[int(input())]}\n")
|
from sys import stdin,stdout
input = lambda : stdin.readline().rstrip()
print =lambda x : stdout.write(str(x))
dp = [0 for _ in range(40002)]
dp[0] = 1
for i in range(1, 40001):
if str(i) == str(i)[::-1]:
for j in range(i, 40001):
{{completion}}
for _ in range(int(input())):
print(f"{dp[int(input())]}\n")
|
dp[j] = (dp[j]+dp[j-i])%int(1e9+7)
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004783
|
block
|
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:
R=range
m=40001
d=10**9+7
p=[]
for i in R(1,m):
n=str(i)
if n==n[::-1]:# TODO: Your code here
a=[1]+[0]*m
for i in p:
for j in R(i,m):
a[j]+=a[j-i];a[j]%=d
for n in[*open(0)][1:]:print(a[int(n)])
|
R=range
m=40001
d=10**9+7
p=[]
for i in R(1,m):
n=str(i)
if n==n[::-1]:{{completion}}
a=[1]+[0]*m
for i in p:
for j in R(i,m):
a[j]+=a[j-i];a[j]%=d
for n in[*open(0)][1:]:print(a[int(n)])
|
p+=[i]
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004784
|
block
|
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:
R=range
m=40001
d=10**9+7
p=[]
for i in R(1,m):
n=str(i)
if n==n[::-1]:p+=[i]
a=[1]+[0]*m
for i in p:
for j in R(i,m):
# TODO: Your code here
for n in[*open(0)][1:]:print(a[int(n)])
|
R=range
m=40001
d=10**9+7
p=[]
for i in R(1,m):
n=str(i)
if n==n[::-1]:p+=[i]
a=[1]+[0]*m
for i in p:
for j in R(i,m):
{{completion}}
for n in[*open(0)][1:]:print(a[int(n)])
|
a[j]+=a[j-i];a[j]%=d
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004785
|
block
|
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: 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:
d=[0]*40001
d[0]=1
for x in range(1,40001):
if str(x)==str(x)[::-1]:
for i in range(x,40001):
# TODO: Your code here
for _ in range(int(input())):
print(d[int(input())])
|
d=[0]*40001
d[0]=1
for x in range(1,40001):
if str(x)==str(x)[::-1]:
for i in range(x,40001):
{{completion}}
for _ in range(int(input())):
print(d[int(input())])
|
d[i]=(d[i]+d[i-x])%(10**9+7)
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004787
|
block
|
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:
size = int(4e4)+1
ps=[]
i=1
while (i<size):
if str(i) == str(i)[::-1]:
ps.append(i)
i+=1
pm = [0]*size
pm[0]=1
for p in ps:
i=0
while (i<size):
if i+p >= size:
# TODO: Your code here
pm[i+p]+=pm[i]
pm[i+p]%=int(1e9)+7
i+=1
T = int(input())
for _ in range(T):
n = int(input())
print(pm[n])
|
size = int(4e4)+1
ps=[]
i=1
while (i<size):
if str(i) == str(i)[::-1]:
ps.append(i)
i+=1
pm = [0]*size
pm[0]=1
for p in ps:
i=0
while (i<size):
if i+p >= size:
{{completion}}
pm[i+p]+=pm[i]
pm[i+p]%=int(1e9)+7
i+=1
T = int(input())
for _ in range(T):
n = int(input())
print(pm[n])
|
break
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
block_completion_004788
|
block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.