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: There is a chip on the coordinate line. Initially, the chip is located at the point $$$0$$$. You can perform any number of moves; each move increases the coordinate of the chip by some positive integer (which is called the length of the move). The length of the first move you make should be divisible by $$$k$$$, the length of the second move — by $$$k+1$$$, the third — by $$$k+2$$$, and so on.For example, if $$$k=2$$$, then the sequence of moves may look like this: $$$0 \rightarrow 4 \rightarrow 7 \rightarrow 19 \rightarrow 44$$$, because $$$4 - 0 = 4$$$ is divisible by $$$2 = k$$$, $$$7 - 4 = 3$$$ is divisible by $$$3 = k + 1$$$, $$$19 - 7 = 12$$$ is divisible by $$$4 = k + 2$$$, $$$44 - 19 = 25$$$ is divisible by $$$5 = k + 3$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Your task is to count the number of ways to reach the point $$$x$$$, starting from $$$0$$$, for every $$$x \in [1, n]$$$. The number of ways can be very large, so print it modulo $$$998244353$$$. Two ways are considered different if they differ as sets of visited positions.
Input Specification: The first (and only) line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$).
Output Specification: Print $$$n$$$ integers — the number of ways to reach the point $$$x$$$, starting from $$$0$$$, for every $$$x \in [1, n]$$$, taken modulo $$$998244353$$$.
Notes: NoteLet's look at the first example:Ways to reach the point $$$1$$$: $$$[0, 1]$$$;Ways to reach the point $$$2$$$: $$$[0, 2]$$$;Ways to reach the point $$$3$$$: $$$[0, 1, 3]$$$, $$$[0, 3]$$$;Ways to reach the point $$$4$$$: $$$[0, 2, 4]$$$, $$$[0, 4]$$$;Ways to reach the point $$$5$$$: $$$[0, 1, 5]$$$, $$$[0, 3, 5]$$$, $$$[0, 5]$$$;Ways to reach the point $$$6$$$: $$$[0, 1, 3, 6]$$$, $$$[0, 2, 6]$$$, $$$[0, 4, 6]$$$, $$$[0, 6]$$$;Ways to reach the point $$$7$$$: $$$[0, 2, 4, 7]$$$, $$$[0, 1, 7]$$$, $$$[0, 3, 7]$$$, $$$[0, 5, 7]$$$, $$$[0, 7]$$$;Ways to reach the point $$$8$$$: $$$[0, 3, 5, 8]$$$, $$$[0, 1, 5, 8]$$$, $$$[0, 2, 8]$$$, $$$[0, 4, 8]$$$, $$$[0, 6, 8]$$$, $$$[0, 8]$$$.
Code:
n,k=map(int,input().split());M=998244353
f,z=[1]+[0]*n,[0]*(n+1);l=0
while l<=n-k:
s=[0]*k
for # TODO: Your code here:
j=i%k
s[j],f[i],z[i]=(s[j]+f[i])%M,s[j],(z[i]+s[j])%M
l+=k;k+=1
print(*z[1:])
|
n,k=map(int,input().split());M=998244353
f,z=[1]+[0]*n,[0]*(n+1);l=0
while l<=n-k:
s=[0]*k
for {{completion}}:
j=i%k
s[j],f[i],z[i]=(s[j]+f[i])%M,s[j],(z[i]+s[j])%M
l+=k;k+=1
print(*z[1:])
|
i in range(l,n+1)
|
[{"input": "8 1", "output": ["1 1 2 2 3 4 5 6"]}, {"input": "10 2", "output": ["0 1 0 1 1 1 1 2 2 2"]}]
|
control_completion_008076
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that?
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more.
Code:
def readline():
line = input()
while not line:
line = input()
return line
def main():
t = int(readline())
for _ in range(t):
m = int(readline())
a = [ [], [] ]
a[0] += list(map(int, readline().split()))
a[1] = list(map(int, readline().split()))
h = [ [None] * m, [None] * m ]
h[0][m-1] = max(a[1][m-1]+1, a[0][m-1]+1+1)
h[1][m-1] = max(a[0][m-1]+1, a[1][m-1]+1+1)
for i in reversed(range(m-1)):
h[0][i] = max(a[1][i]+1, h[0][i+1]+1, a[0][i]+(i!=0)+(m-i-1)*2+1)
h[1][i] = max(a[0][i]+1, h[1][i+1]+1, a[1][i]+1+(m-i-1)*2+1)
pos = (0,0)
t = 0
best_total_time = 10**10
for i in range(2*m-1):
if i % 2 == 0:
total_time = max(t+(m-i//2-1)*2+1, h[pos[0]][pos[1]])
# print(pos, t,total_time)
best_total_time = min(best_total_time, total_time)
if i % 4 == 0:
# abajo
pos = (pos[0]+1, pos[1])
elif # TODO: Your code here:
# derecha
pos = (pos[0], pos[1]+1)
elif (i-2) % 4 == 0:
# arr
pos = (pos[0]-1, pos[1])
elif (i-3) % 4 == 0:
# derecha
pos = (pos[0], pos[1]+1)
t = max(a[pos[0]][pos[1]] + 1, t+1)
# for line in h:
# print(line)
print(best_total_time)
main()
|
def readline():
line = input()
while not line:
line = input()
return line
def main():
t = int(readline())
for _ in range(t):
m = int(readline())
a = [ [], [] ]
a[0] += list(map(int, readline().split()))
a[1] = list(map(int, readline().split()))
h = [ [None] * m, [None] * m ]
h[0][m-1] = max(a[1][m-1]+1, a[0][m-1]+1+1)
h[1][m-1] = max(a[0][m-1]+1, a[1][m-1]+1+1)
for i in reversed(range(m-1)):
h[0][i] = max(a[1][i]+1, h[0][i+1]+1, a[0][i]+(i!=0)+(m-i-1)*2+1)
h[1][i] = max(a[0][i]+1, h[1][i+1]+1, a[1][i]+1+(m-i-1)*2+1)
pos = (0,0)
t = 0
best_total_time = 10**10
for i in range(2*m-1):
if i % 2 == 0:
total_time = max(t+(m-i//2-1)*2+1, h[pos[0]][pos[1]])
# print(pos, t,total_time)
best_total_time = min(best_total_time, total_time)
if i % 4 == 0:
# abajo
pos = (pos[0]+1, pos[1])
elif {{completion}}:
# derecha
pos = (pos[0], pos[1]+1)
elif (i-2) % 4 == 0:
# arr
pos = (pos[0]-1, pos[1])
elif (i-3) % 4 == 0:
# derecha
pos = (pos[0], pos[1]+1)
t = max(a[pos[0]][pos[1]] + 1, t+1)
# for line in h:
# print(line)
print(best_total_time)
main()
|
(i-1) % 4 == 0
|
[{"input": "4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0", "output": ["5\n19\n17\n3"]}]
|
control_completion_008132
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that?
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more.
Code:
def readline():
line = input()
while not line:
line = input()
return line
def main():
t = int(readline())
for _ in range(t):
m = int(readline())
a = [ [], [] ]
a[0] += list(map(int, readline().split()))
a[1] = list(map(int, readline().split()))
h = [ [None] * m, [None] * m ]
h[0][m-1] = max(a[1][m-1]+1, a[0][m-1]+1+1)
h[1][m-1] = max(a[0][m-1]+1, a[1][m-1]+1+1)
for i in reversed(range(m-1)):
h[0][i] = max(a[1][i]+1, h[0][i+1]+1, a[0][i]+(i!=0)+(m-i-1)*2+1)
h[1][i] = max(a[0][i]+1, h[1][i+1]+1, a[1][i]+1+(m-i-1)*2+1)
pos = (0,0)
t = 0
best_total_time = 10**10
for i in range(2*m-1):
if i % 2 == 0:
total_time = max(t+(m-i//2-1)*2+1, h[pos[0]][pos[1]])
# print(pos, t,total_time)
best_total_time = min(best_total_time, total_time)
if i % 4 == 0:
# abajo
pos = (pos[0]+1, pos[1])
elif (i-1) % 4 == 0:
# derecha
pos = (pos[0], pos[1]+1)
elif # TODO: Your code here:
# arr
pos = (pos[0]-1, pos[1])
elif (i-3) % 4 == 0:
# derecha
pos = (pos[0], pos[1]+1)
t = max(a[pos[0]][pos[1]] + 1, t+1)
# for line in h:
# print(line)
print(best_total_time)
main()
|
def readline():
line = input()
while not line:
line = input()
return line
def main():
t = int(readline())
for _ in range(t):
m = int(readline())
a = [ [], [] ]
a[0] += list(map(int, readline().split()))
a[1] = list(map(int, readline().split()))
h = [ [None] * m, [None] * m ]
h[0][m-1] = max(a[1][m-1]+1, a[0][m-1]+1+1)
h[1][m-1] = max(a[0][m-1]+1, a[1][m-1]+1+1)
for i in reversed(range(m-1)):
h[0][i] = max(a[1][i]+1, h[0][i+1]+1, a[0][i]+(i!=0)+(m-i-1)*2+1)
h[1][i] = max(a[0][i]+1, h[1][i+1]+1, a[1][i]+1+(m-i-1)*2+1)
pos = (0,0)
t = 0
best_total_time = 10**10
for i in range(2*m-1):
if i % 2 == 0:
total_time = max(t+(m-i//2-1)*2+1, h[pos[0]][pos[1]])
# print(pos, t,total_time)
best_total_time = min(best_total_time, total_time)
if i % 4 == 0:
# abajo
pos = (pos[0]+1, pos[1])
elif (i-1) % 4 == 0:
# derecha
pos = (pos[0], pos[1]+1)
elif {{completion}}:
# arr
pos = (pos[0]-1, pos[1])
elif (i-3) % 4 == 0:
# derecha
pos = (pos[0], pos[1]+1)
t = max(a[pos[0]][pos[1]] + 1, t+1)
# for line in h:
# print(line)
print(best_total_time)
main()
|
(i-2) % 4 == 0
|
[{"input": "4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0", "output": ["5\n19\n17\n3"]}]
|
control_completion_008133
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array.
Input Specification: The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query.
Output Specification: For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query.
Notes: NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$.
Code:
import sys; input = sys.stdin.readline
def seg(start, end):
if # TODO: Your code here:
val = max(arr[start], 0)
return [(val, val, val, arr[start])]
mid = (start + end) // 2
l = seg(start, mid)
r = seg(mid + 1, end)
result = []
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
l, r = r, l
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
return result
n = int(input())
l = 1 << n
arr = list(map(int, input().split()))
tree = seg(0, l - 1)
i = 0
for _ in range(int(input())):
i ^= (1 << int(input()))
print(tree[i][0])
|
import sys; input = sys.stdin.readline
def seg(start, end):
if {{completion}}:
val = max(arr[start], 0)
return [(val, val, val, arr[start])]
mid = (start + end) // 2
l = seg(start, mid)
r = seg(mid + 1, end)
result = []
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
l, r = r, l
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
return result
n = int(input())
l = 1 << n
arr = list(map(int, input().split()))
tree = seg(0, l - 1)
i = 0
for _ in range(int(input())):
i ^= (1 << int(input()))
print(tree[i][0])
|
start == end
|
[{"input": "3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1", "output": ["18\n8\n13"]}]
|
control_completion_008160
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array.
Input Specification: The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query.
Output Specification: For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query.
Notes: NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$.
Code:
import sys; input = sys.stdin.readline
def seg(start, end):
if start == end:
val = max(arr[start], 0)
return [(val, val, val, arr[start])]
mid = (start + end) // 2
l = seg(start, mid)
r = seg(mid + 1, end)
result = []
for # TODO: Your code here:
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
l, r = r, l
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
return result
n = int(input())
l = 1 << n
arr = list(map(int, input().split()))
tree = seg(0, l - 1)
i = 0
for _ in range(int(input())):
i ^= (1 << int(input()))
print(tree[i][0])
|
import sys; input = sys.stdin.readline
def seg(start, end):
if start == end:
val = max(arr[start], 0)
return [(val, val, val, arr[start])]
mid = (start + end) // 2
l = seg(start, mid)
r = seg(mid + 1, end)
result = []
for {{completion}}:
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
l, r = r, l
for i in range((end - start + 1) // 2):
lb, ls, lp, lS = l[i]
rb, rs, rp, rS = r[i]
result.append((max(lb, rb, ls + rp), max(rs, rS + ls), max(lp, lS + rp), lS + rS))
return result
n = int(input())
l = 1 << n
arr = list(map(int, input().split()))
tree = seg(0, l - 1)
i = 0
for _ in range(int(input())):
i ^= (1 << int(input()))
print(tree[i][0])
|
i in range((end - start + 1) // 2)
|
[{"input": "3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1", "output": ["18\n8\n13"]}]
|
control_completion_008161
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array.
Input Specification: The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query.
Output Specification: For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query.
Notes: NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$.
Code:
import sys
input = lambda: sys.stdin.readline().rstrip()
class Node:
def __init__(self, seg, suf, pref, sum) -> None:
self.best = seg
self.suf = suf
self.pref = pref
self.sum = sum
def merge(a, b):
seg = max(a.best, b.best, a.suf + b.pref)
suf = max(b.suf, b.sum + a.suf)
pref = max(a.pref, a.sum + b.pref)
sum = a.sum + b.sum
return Node(seg, suf, pref, sum)
def single(a):
v = max(a, 0)
return Node(v, v, v, a)
def build(v, l, r):
if l + 1 == r:
return [single(A[l])]
else:
m = (l + r) // 2
vl = build(2 * v + 1, l, m)
vr = build(2 * v + 2, m, r)
ans = []
for _ in range(2):
for # TODO: Your code here:
ans.append(merge(vl[i], vr[i]))
vl, vr = vr, vl
return ans
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
M = 1 << N
tree = build(0, 0, M)
curr = 0
for _ in range(Q):
K = int(input())
curr ^= (1 << K)
print(tree[curr].best)
|
import sys
input = lambda: sys.stdin.readline().rstrip()
class Node:
def __init__(self, seg, suf, pref, sum) -> None:
self.best = seg
self.suf = suf
self.pref = pref
self.sum = sum
def merge(a, b):
seg = max(a.best, b.best, a.suf + b.pref)
suf = max(b.suf, b.sum + a.suf)
pref = max(a.pref, a.sum + b.pref)
sum = a.sum + b.sum
return Node(seg, suf, pref, sum)
def single(a):
v = max(a, 0)
return Node(v, v, v, a)
def build(v, l, r):
if l + 1 == r:
return [single(A[l])]
else:
m = (l + r) // 2
vl = build(2 * v + 1, l, m)
vr = build(2 * v + 2, m, r)
ans = []
for _ in range(2):
for {{completion}}:
ans.append(merge(vl[i], vr[i]))
vl, vr = vr, vl
return ans
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
M = 1 << N
tree = build(0, 0, M)
curr = 0
for _ in range(Q):
K = int(input())
curr ^= (1 << K)
print(tree[curr].best)
|
i in range((r - l) // 2)
|
[{"input": "3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1", "output": ["18\n8\n13"]}]
|
control_completion_008162
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider a hallway, which can be represented as the matrix with $$$2$$$ rows and $$$n$$$ columns. Let's denote the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$. The distance between the cells $$$(i_1, j_1)$$$ and $$$(i_2, j_2)$$$ is $$$|i_1 - i_2| + |j_1 - j_2|$$$.There is a cleaning robot in the cell $$$(1, 1)$$$. Some cells of the hallway are clean, other cells are dirty (the cell with the robot is clean). You want to clean the hallway, so you are going to launch the robot to do this.After the robot is launched, it works as follows. While at least one cell is dirty, the robot chooses the closest (to its current cell) cell among those which are dirty, moves there and cleans it (so the cell is no longer dirty). After cleaning a cell, the robot again finds the closest dirty cell to its current cell, and so on. This process repeats until the whole hallway is clean.However, there is a critical bug in the robot's program. If at some moment, there are multiple closest (to the robot's current position) dirty cells, the robot malfunctions.You want to clean the hallway in such a way that the robot doesn't malfunction. Before launching the robot, you can clean some (possibly zero) of the dirty cells yourself. However, you don't want to do too much dirty work yourself while you have this nice, smart (yet buggy) robot to do this. Note that you cannot make a clean cell dirty.Calculate the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of columns in the hallway. Then two lines follow, denoting the $$$1$$$-st and the $$$2$$$-nd row of the hallway. These lines contain $$$n$$$ characters each, where 0 denotes a clean cell and 1 denotes a dirty cell. The starting cell of the robot $$$(1, 1)$$$ is clean.
Output Specification: Print one integer — the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.
Notes: NoteIn the first example, you can clean the cell $$$(1, 2)$$$, so the path of the robot is $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2)$$$.In the second example, you can leave the hallway as it is, so the path of the robot is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2)$$$.In the third example, you can clean the cell $$$(1, 2)$$$, so the path of the robot is $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (1, 4)$$$.In the fourth example, the hallway is already clean. Maybe you have launched the robot earlier?
Code:
import sys
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
G = [[int(x) for x in input()] + [0] for _ in range(2)]
dp = [[0] * 2 for _ in range(N + 1)] # number of 1 cells robot will clean when it arrives at cell (j, i) from the left
for j in range(2):
dp[N - 1][j] = G[1 - j][N - 1]
for i in range(N - 2, - 1, -1):
for j in range(2):
dp[i][j] = G[j][i + 1] + dp[i + 1][j] # base case: ignore row 1 - j and proceed right
if # TODO: Your code here:
dp[i][j] = max(dp[i][j], 1 + G[1 - j][i + 1] + G[1 - j][i + 2] + dp[i + 2][1 - j])
print(dp[0][0])
return
solve()
|
import sys
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
G = [[int(x) for x in input()] + [0] for _ in range(2)]
dp = [[0] * 2 for _ in range(N + 1)] # number of 1 cells robot will clean when it arrives at cell (j, i) from the left
for j in range(2):
dp[N - 1][j] = G[1 - j][N - 1]
for i in range(N - 2, - 1, -1):
for j in range(2):
dp[i][j] = G[j][i + 1] + dp[i + 1][j] # base case: ignore row 1 - j and proceed right
if {{completion}}:
dp[i][j] = max(dp[i][j], 1 + G[1 - j][i + 1] + G[1 - j][i + 2] + dp[i + 2][1 - j])
print(dp[0][0])
return
solve()
|
G[1 - j][i]
|
[{"input": "2\n01\n11", "output": ["2"]}, {"input": "2\n01\n01", "output": ["2"]}, {"input": "4\n0101\n1011", "output": ["4"]}, {"input": "4\n0000\n0000", "output": ["0"]}, {"input": "5\n00011\n10101", "output": ["4"]}, {"input": "6\n011111\n111111", "output": ["8"]}, {"input": "10\n0101001010\n1010100110", "output": ["6"]}]
|
control_completion_008234
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider a hallway, which can be represented as the matrix with $$$2$$$ rows and $$$n$$$ columns. Let's denote the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$. The distance between the cells $$$(i_1, j_1)$$$ and $$$(i_2, j_2)$$$ is $$$|i_1 - i_2| + |j_1 - j_2|$$$.There is a cleaning robot in the cell $$$(1, 1)$$$. Some cells of the hallway are clean, other cells are dirty (the cell with the robot is clean). You want to clean the hallway, so you are going to launch the robot to do this.After the robot is launched, it works as follows. While at least one cell is dirty, the robot chooses the closest (to its current cell) cell among those which are dirty, moves there and cleans it (so the cell is no longer dirty). After cleaning a cell, the robot again finds the closest dirty cell to its current cell, and so on. This process repeats until the whole hallway is clean.However, there is a critical bug in the robot's program. If at some moment, there are multiple closest (to the robot's current position) dirty cells, the robot malfunctions.You want to clean the hallway in such a way that the robot doesn't malfunction. Before launching the robot, you can clean some (possibly zero) of the dirty cells yourself. However, you don't want to do too much dirty work yourself while you have this nice, smart (yet buggy) robot to do this. Note that you cannot make a clean cell dirty.Calculate the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of columns in the hallway. Then two lines follow, denoting the $$$1$$$-st and the $$$2$$$-nd row of the hallway. These lines contain $$$n$$$ characters each, where 0 denotes a clean cell and 1 denotes a dirty cell. The starting cell of the robot $$$(1, 1)$$$ is clean.
Output Specification: Print one integer — the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.
Notes: NoteIn the first example, you can clean the cell $$$(1, 2)$$$, so the path of the robot is $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2)$$$.In the second example, you can leave the hallway as it is, so the path of the robot is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2)$$$.In the third example, you can clean the cell $$$(1, 2)$$$, so the path of the robot is $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (1, 4)$$$.In the fourth example, the hallway is already clean. Maybe you have launched the robot earlier?
Code:
import sys
inf = float('inf')
mod = 998244353
input = lambda: sys.stdin.readline().rstrip()
inpnm = lambda: map(int, input().split())
inparr = lambda: [int(i) for i in input().split()]
inpint = lambda: int(input())
n=inpint()
s=[]
for i in range(2):
s.append([i for i in list(input())]+['0','0'])
#print(arr)
f=[[-inf]*(2) for _ in range(n+2)]
f[0][0]=0
for i in range(n):
for j in range(2):
f[i+1][j]=max(f[i+1][j],f[i][j]+int(s[j][i+1]))
if # TODO: Your code here:
f[min(i+2,n)][j^1]=max(f[min(i+2,n)][j^1],f[i][j]+1+int(s[j^1][i+1])+int(s[j^1][i+2]))
print(max(f[n][0],f[n][1]))
|
import sys
inf = float('inf')
mod = 998244353
input = lambda: sys.stdin.readline().rstrip()
inpnm = lambda: map(int, input().split())
inparr = lambda: [int(i) for i in input().split()]
inpint = lambda: int(input())
n=inpint()
s=[]
for i in range(2):
s.append([i for i in list(input())]+['0','0'])
#print(arr)
f=[[-inf]*(2) for _ in range(n+2)]
f[0][0]=0
for i in range(n):
for j in range(2):
f[i+1][j]=max(f[i+1][j],f[i][j]+int(s[j][i+1]))
if {{completion}}:
f[min(i+2,n)][j^1]=max(f[min(i+2,n)][j^1],f[i][j]+1+int(s[j^1][i+1])+int(s[j^1][i+2]))
print(max(f[n][0],f[n][1]))
|
s[j^1][i]=='1'
|
[{"input": "2\n01\n11", "output": ["2"]}, {"input": "2\n01\n01", "output": ["2"]}, {"input": "4\n0101\n1011", "output": ["4"]}, {"input": "4\n0000\n0000", "output": ["0"]}, {"input": "5\n00011\n10101", "output": ["4"]}, {"input": "6\n011111\n111111", "output": ["8"]}, {"input": "10\n0101001010\n1010100110", "output": ["6"]}]
|
control_completion_008235
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider a hallway, which can be represented as the matrix with $$$2$$$ rows and $$$n$$$ columns. Let's denote the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$. The distance between the cells $$$(i_1, j_1)$$$ and $$$(i_2, j_2)$$$ is $$$|i_1 - i_2| + |j_1 - j_2|$$$.There is a cleaning robot in the cell $$$(1, 1)$$$. Some cells of the hallway are clean, other cells are dirty (the cell with the robot is clean). You want to clean the hallway, so you are going to launch the robot to do this.After the robot is launched, it works as follows. While at least one cell is dirty, the robot chooses the closest (to its current cell) cell among those which are dirty, moves there and cleans it (so the cell is no longer dirty). After cleaning a cell, the robot again finds the closest dirty cell to its current cell, and so on. This process repeats until the whole hallway is clean.However, there is a critical bug in the robot's program. If at some moment, there are multiple closest (to the robot's current position) dirty cells, the robot malfunctions.You want to clean the hallway in such a way that the robot doesn't malfunction. Before launching the robot, you can clean some (possibly zero) of the dirty cells yourself. However, you don't want to do too much dirty work yourself while you have this nice, smart (yet buggy) robot to do this. Note that you cannot make a clean cell dirty.Calculate the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of columns in the hallway. Then two lines follow, denoting the $$$1$$$-st and the $$$2$$$-nd row of the hallway. These lines contain $$$n$$$ characters each, where 0 denotes a clean cell and 1 denotes a dirty cell. The starting cell of the robot $$$(1, 1)$$$ is clean.
Output Specification: Print one integer — the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.
Notes: NoteIn the first example, you can clean the cell $$$(1, 2)$$$, so the path of the robot is $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2)$$$.In the second example, you can leave the hallway as it is, so the path of the robot is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2)$$$.In the third example, you can clean the cell $$$(1, 2)$$$, so the path of the robot is $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (1, 4)$$$.In the fourth example, the hallway is already clean. Maybe you have launched the robot earlier?
Code:
import sys
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
G = [[int(x) for x in input()] + [0] for _ in range(2)]
dp = [[0] * 2 for _ in range(N + 1)]
for j in range(2):
dp[N - 1][j] = G[1 - j][N - 1]
for i in range(N - 2, - 1, -1):
for j in range(2):
dp[i][j] = G[j][i + 1] + dp[i + 1][j] # can always ignore row 1 - j and proceed right
if G[1 - j][i]:
if # TODO: Your code here:
dp[i][j] = max(dp[i][j], 1 + G[1 - j][i + 1] + G[1 - j][i + 2] + dp[i + 2][1 - j])
else:
dp[i][j] = max(dp[i][j], 1 + G[1 - j][i + 1] + dp[i + 1][1 - j])
print(dp[0][0])
return
solve()
|
import sys
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
G = [[int(x) for x in input()] + [0] for _ in range(2)]
dp = [[0] * 2 for _ in range(N + 1)]
for j in range(2):
dp[N - 1][j] = G[1 - j][N - 1]
for i in range(N - 2, - 1, -1):
for j in range(2):
dp[i][j] = G[j][i + 1] + dp[i + 1][j] # can always ignore row 1 - j and proceed right
if G[1 - j][i]:
if {{completion}}:
dp[i][j] = max(dp[i][j], 1 + G[1 - j][i + 1] + G[1 - j][i + 2] + dp[i + 2][1 - j])
else:
dp[i][j] = max(dp[i][j], 1 + G[1 - j][i + 1] + dp[i + 1][1 - j])
print(dp[0][0])
return
solve()
|
G[j][i + 1]
|
[{"input": "2\n01\n11", "output": ["2"]}, {"input": "2\n01\n01", "output": ["2"]}, {"input": "4\n0101\n1011", "output": ["4"]}, {"input": "4\n0000\n0000", "output": ["0"]}, {"input": "5\n00011\n10101", "output": ["4"]}, {"input": "6\n011111\n111111", "output": ["8"]}, {"input": "10\n0101001010\n1010100110", "output": ["6"]}]
|
control_completion_008236
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.
Input Specification: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of columns of the grid. The following two lines each contain a string consisting of $$$n$$$ characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively — the description of the grid.
Output Specification: For each test case, output "YES" if Vasya considers the grid's two rows to be identical, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Notes: NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same.
Code:
import sys
if __name__ == "__main__":
input_arr = sys.stdin.read().split()
tc = int(input_arr[0])
pos = 1
for i in range(tc):
n, row1, row2 = input_arr[pos:pos + 3]
row1n, row2n = [], []
for k,j in zip(row1, row2):
if # TODO: Your code here:
k = "B"
if j == "G":
j = "B"
row1n.append(k)
row2n.append(j)
print("YES" if row1n == row2n else "NO")
pos += 3
# '6 2 RG RB 4 GRBG GBGB 5 GGGGG BBBBB 7 BBBBBBB RRRRRRR 8 RGBRRGBR RGGRRBGR 1 G G'
|
import sys
if __name__ == "__main__":
input_arr = sys.stdin.read().split()
tc = int(input_arr[0])
pos = 1
for i in range(tc):
n, row1, row2 = input_arr[pos:pos + 3]
row1n, row2n = [], []
for k,j in zip(row1, row2):
if {{completion}}:
k = "B"
if j == "G":
j = "B"
row1n.append(k)
row2n.append(j)
print("YES" if row1n == row2n else "NO")
pos += 3
# '6 2 RG RB 4 GRBG GBGB 5 GGGGG BBBBB 7 BBBBBBB RRRRRRR 8 RGBRRGBR RGGRRBGR 1 G G'
|
k == "G"
|
[{"input": "6\n\n2\n\nRG\n\nRB\n\n4\n\nGRBG\n\nGBGB\n\n5\n\nGGGGG\n\nBBBBB\n\n7\n\nBBBBBBB\n\nRRRRRRR\n\n8\n\nRGBRRGBR\n\nRGGRRBGR\n\n1\n\nG\n\nG", "output": ["YES\nNO\nYES\nNO\nYES\nYES"]}]
|
control_completion_008313
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.
Input Specification: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of columns of the grid. The following two lines each contain a string consisting of $$$n$$$ characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively — the description of the grid.
Output Specification: For each test case, output "YES" if Vasya considers the grid's two rows to be identical, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Notes: NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same.
Code:
import sys
if __name__ == "__main__":
input_arr = sys.stdin.read().split()
tc = int(input_arr[0])
pos = 1
for i in range(tc):
n, row1, row2 = input_arr[pos:pos + 3]
row1n, row2n = [], []
for k,j in zip(row1, row2):
if k == "G":
k = "B"
if # TODO: Your code here:
j = "B"
row1n.append(k)
row2n.append(j)
print("YES" if row1n == row2n else "NO")
pos += 3
# '6 2 RG RB 4 GRBG GBGB 5 GGGGG BBBBB 7 BBBBBBB RRRRRRR 8 RGBRRGBR RGGRRBGR 1 G G'
|
import sys
if __name__ == "__main__":
input_arr = sys.stdin.read().split()
tc = int(input_arr[0])
pos = 1
for i in range(tc):
n, row1, row2 = input_arr[pos:pos + 3]
row1n, row2n = [], []
for k,j in zip(row1, row2):
if k == "G":
k = "B"
if {{completion}}:
j = "B"
row1n.append(k)
row2n.append(j)
print("YES" if row1n == row2n else "NO")
pos += 3
# '6 2 RG RB 4 GRBG GBGB 5 GGGGG BBBBB 7 BBBBBBB RRRRRRR 8 RGBRRGBR RGGRRBGR 1 G G'
|
j == "G"
|
[{"input": "6\n\n2\n\nRG\n\nRB\n\n4\n\nGRBG\n\nGBGB\n\n5\n\nGGGGG\n\nBBBBB\n\n7\n\nBBBBBBB\n\nRRRRRRR\n\n8\n\nRGBRRGBR\n\nRGGRRBGR\n\n1\n\nG\n\nG", "output": ["YES\nNO\nYES\nNO\nYES\nYES"]}]
|
control_completion_008314
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet: if the letter number is single-digit number (less than $$$10$$$), then just writes it out; if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows: 'c' — is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3); 'o' — is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150); 'd' — is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504); 'e' — is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).
Input Specification: The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ — the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.
Output Specification: For each test case output the required string $$$s$$$ — the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.
Notes: NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120.
Code:
import sys
if __name__ == "__main__":
input_arr = list(map(int, sys.stdin.read().split()))
n = input_arr[0]
pos = 1
for i in range(n):
n, code = input_arr[pos:pos+2]
code_str = str(code)
result = []
j = n-1
while j >= 0:
if j >= 2:
sub = code_str[j-2:j+1]
if # TODO: Your code here:
result.append(chr(int(sub)//10 + 96))
j -= 3
else:
result.append(chr(int(code_str[j])+96))
j -= 1
else:
result.append(chr(int(code_str[j]) + 96))
j -= 1
print("".join(result[::-1]))
pos += 2
# sys.stdin.read()
|
import sys
if __name__ == "__main__":
input_arr = list(map(int, sys.stdin.read().split()))
n = input_arr[0]
pos = 1
for i in range(n):
n, code = input_arr[pos:pos+2]
code_str = str(code)
result = []
j = n-1
while j >= 0:
if j >= 2:
sub = code_str[j-2:j+1]
if {{completion}}:
result.append(chr(int(sub)//10 + 96))
j -= 3
else:
result.append(chr(int(code_str[j])+96))
j -= 1
else:
result.append(chr(int(code_str[j]) + 96))
j -= 1
print("".join(result[::-1]))
pos += 2
# sys.stdin.read()
|
sub[-1] == "0"
|
[{"input": "9\n\n6\n\n315045\n\n4\n\n1100\n\n7\n\n1213121\n\n6\n\n120120\n\n18\n\n315045615018035190\n\n7\n\n1111110\n\n7\n\n1111100\n\n5\n\n11111\n\n4\n\n2606", "output": ["code\naj\nabacaba\nll\ncodeforces\naaaak\naaaaj\naaaaa\nzf"]}]
|
control_completion_008430
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet: if the letter number is single-digit number (less than $$$10$$$), then just writes it out; if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows: 'c' — is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3); 'o' — is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150); 'd' — is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504); 'e' — is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).
Input Specification: The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ — the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.
Output Specification: For each test case output the required string $$$s$$$ — the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.
Notes: NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120.
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()
s = str(inp1())[::-1]
alph = "0abcdefghijklmnopqrstuvwxyz"
d = deque()
i = 0
while i < n:
if # TODO: Your code here:
d.appendleft(int(s[i + 1:i + 3][::-1]))
i += 3
else:
d.appendleft(int(s[i]))
i += 1
ret = ""
for i in d:
ret += alph[i]
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()
s = str(inp1())[::-1]
alph = "0abcdefghijklmnopqrstuvwxyz"
d = deque()
i = 0
while i < n:
if {{completion}}:
d.appendleft(int(s[i + 1:i + 3][::-1]))
i += 3
else:
d.appendleft(int(s[i]))
i += 1
ret = ""
for i in d:
ret += alph[i]
print(ret)
|
s[i] == "0"
|
[{"input": "9\n\n6\n\n315045\n\n4\n\n1100\n\n7\n\n1213121\n\n6\n\n120120\n\n18\n\n315045615018035190\n\n7\n\n1111110\n\n7\n\n1111100\n\n5\n\n11111\n\n4\n\n2606", "output": ["code\naj\nabacaba\nll\ncodeforces\naaaak\naaaaj\naaaaa\nzf"]}]
|
control_completion_008431
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Vlad went into his appartment house entrance, now he is on the $$$1$$$-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that: the first elevator is currently on the floor $$$a$$$ (it is currently motionless), the second elevator is located on floor $$$b$$$ and goes to floor $$$c$$$ ($$$b \ne c$$$). Please note, if $$$b=1$$$, then the elevator is already leaving the floor $$$1$$$ and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor $$$1$$$. If you call the second one, then first it will reach the floor $$$c$$$ and only then it will go to the floor $$$1$$$. It takes $$$|x - y|$$$ seconds for each elevator to move from floor $$$x$$$ to floor $$$y$$$.Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.
Input Specification: The first line of the input contains the only $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. This is followed by $$$t$$$ lines, three integers each $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$, $$$b \ne c$$$) — floor numbers described in the statement.
Output Specification: Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. As an answer, output: $$$1$$$, if it is better to call the first elevator; $$$2$$$, if it is better to call the second one; $$$3$$$, if it doesn't matter which elevator to call (both elevators will arrive in the same time).
Notes: NoteIn the first test case of the example, the first elevator is already on the floor of $$$1$$$.In the second test case of the example, when called, the elevators would move as follows: At the time of the call, the first elevator is on the floor of $$$3$$$, and the second one is on the floor of $$$1$$$, but is already going to another floor; in $$$1$$$ second after the call, the first elevator would be on the floor $$$2$$$, the second one would also reach the floor $$$2$$$ and now can go to the floor $$$1$$$; in $$$2$$$ seconds, any elevator would reach the floor $$$1$$$. In the third test case of the example, the first elevator will arrive in $$$2$$$ seconds, and the second in $$$1$$$.
Code:
import sys
def calculate(x, y1, y2):
x = int(x)
y1 = int(y1)
y2 = int(y2)
diff1 = abs(x - 1)
diff2 = abs(y1-y2) if y2 == 1 else abs(y1-y2)+y2-1
if diff1 < diff2:
return 1
elif diff2 < diff1:
return 2
else:
return 3
if __name__ == "__main__":
for line in sys.stdin:
input = line.split()
if # TODO: Your code here:
print(calculate(input[0], input[1], input[2]))
|
import sys
def calculate(x, y1, y2):
x = int(x)
y1 = int(y1)
y2 = int(y2)
diff1 = abs(x - 1)
diff2 = abs(y1-y2) if y2 == 1 else abs(y1-y2)+y2-1
if diff1 < diff2:
return 1
elif diff2 < diff1:
return 2
else:
return 3
if __name__ == "__main__":
for line in sys.stdin:
input = line.split()
if {{completion}}:
print(calculate(input[0], input[1], input[2]))
|
len(input) == 3
|
[{"input": "3\n\n1 2 3\n\n3 1 2\n\n3 2 1", "output": ["1\n3\n2"]}]
|
control_completion_008448
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
Input Specification: The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
Output Specification: For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
Notes: NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Code:
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if tt is None or tt[0] > l[0] + r[0] + 1:
tt = [l[0] + r[0] + 1, r[1]]
elif # TODO: Your code here:
tt[1] = tt[1] + r[1]
d[j][i] = tt
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if tt is None or tt[0] > l[0] + r[0] + 1:
tt = [l[0] + r[0] + 1, r[1]]
elif {{completion}}:
tt[1] = tt[1] + r[1]
d[j][i] = tt
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
tt[0] == l[0] + r[0] + 1
|
[{"input": "8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa", "output": ["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]}]
|
control_completion_008491
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
Input Specification: The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
Output Specification: For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
Notes: NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Code:
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if # TODO: Your code here:
tt = [l[0] + r[0] + 1, r[1]]
elif tt[0] == l[0] + r[0] + 1:
tt[1] = tt[1] + r[1]
d[j][i] = tt
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if {{completion}}:
tt = [l[0] + r[0] + 1, r[1]]
elif tt[0] == l[0] + r[0] + 1:
tt[1] = tt[1] + r[1]
d[j][i] = tt
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
tt is None or tt[0] > l[0] + r[0] + 1
|
[{"input": "8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa", "output": ["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]}]
|
control_completion_008492
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
Input Specification: The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
Output Specification: For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
Notes: NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Code:
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if tt is None or tt[0] > l[0] + r[0] + 1:
tt = [l[0] + r[0] + 1, r[1]]
elif # TODO: Your code here:
tt[1] = tt[1] + r[1]
d[j][i] = tt
else:
break
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if tt is None or tt[0] > l[0] + r[0] + 1:
tt = [l[0] + r[0] + 1, r[1]]
elif {{completion}}:
tt[1] = tt[1] + r[1]
d[j][i] = tt
else:
break
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
tt[0] == l[0] + r[0] + 1
|
[{"input": "8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa", "output": ["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]}]
|
control_completion_008493
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
Input Specification: The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
Output Specification: For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
Notes: NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Code:
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if # TODO: Your code here:
tt = [l[0] + r[0] + 1, r[1]]
elif tt[0] == l[0] + r[0] + 1:
tt[1] = tt[1] + r[1]
d[j][i] = tt
else:
break
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
# from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List, Optional
def solve() -> None:
s = next_token()
t = next_token()
ls = len(s)
lt = len(t)
is_start = [s[i:i + lt] == t for i in range(ls)]
d: List[List[Optional[List[int]]]] = [[None for _ in range(j + 1)] for j in range(ls)]
for ln in range(1, ls + 1):
for j in range(ln - 1, ls):
i = j - ln + 1
for k in range(i, j + 1):
if k + lt - 1 <= j and is_start[k]:
l = (d[k - 1][i] if k - 1 >= i else None) or [0, 1]
if l[0] == 0:
r = (d[j][k + lt] if j >= k + lt else None) or [0, 1]
tt = d[j][i]
if {{completion}}:
tt = [l[0] + r[0] + 1, r[1]]
elif tt[0] == l[0] + r[0] + 1:
tt[1] = tt[1] + r[1]
d[j][i] = tt
else:
break
if d[j][i]:
d[j][i][1] %= 1000000007
print(*(d[ls - 1][0] or [0, 1]))
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
tt is None or tt[0] > l[0] + r[0] + 1
|
[{"input": "8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa", "output": ["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]}]
|
control_completion_008494
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w < n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w < n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
Notes: NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Code:
from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List
def solve() -> None:
a = [int(c) % 9 for c in next_token()]
n = len(a)
sa = list(a)
for i in range(1, n):
sa[i] += sa[i - 1]
w = next_int()
indices = defaultdict(list)
for i in range(w, n + 1):
vlr = ((sa[i - 1] - (sa[i - w - 1] if i - w > 0 else 0)) % 9 + 9) % 9
indices[vlr].append(i - w + 1)
cache = dict()
INF = (n + 1, n)
for _ in range(next_int()):
l = next_int() - 1
r = next_int() - 1
k = next_int()
vlr = ((sa[r] - (sa[l - 1] if l > 0 else 0)) % 9 + 9) % 9
if (vlr, k) not in cache:
res = INF
for v1 in range(9):
for v2 in range(9):
if ((v1 * vlr + v2) % 9 + 9) % 9 == k:
if v1 == v2:
if len(indices[v1]) > 1:
res = min(res, tuple(indices[v1][:2]))
else:
if # TODO: Your code here:
res = min(res, (indices[v1][0], indices[v2][0]))
cache[(vlr, k)] = res if res != INF else (-1, -1)
print(*cache[(vlr, k)])
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List
def solve() -> None:
a = [int(c) % 9 for c in next_token()]
n = len(a)
sa = list(a)
for i in range(1, n):
sa[i] += sa[i - 1]
w = next_int()
indices = defaultdict(list)
for i in range(w, n + 1):
vlr = ((sa[i - 1] - (sa[i - w - 1] if i - w > 0 else 0)) % 9 + 9) % 9
indices[vlr].append(i - w + 1)
cache = dict()
INF = (n + 1, n)
for _ in range(next_int()):
l = next_int() - 1
r = next_int() - 1
k = next_int()
vlr = ((sa[r] - (sa[l - 1] if l > 0 else 0)) % 9 + 9) % 9
if (vlr, k) not in cache:
res = INF
for v1 in range(9):
for v2 in range(9):
if ((v1 * vlr + v2) % 9 + 9) % 9 == k:
if v1 == v2:
if len(indices[v1]) > 1:
res = min(res, tuple(indices[v1][:2]))
else:
if {{completion}}:
res = min(res, (indices[v1][0], indices[v2][0]))
cache[(vlr, k)] = res if res != INF else (-1, -1)
print(*cache[(vlr, k)])
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
len(indices[v1]) > 0 and len(indices[v2]) > 0
|
[{"input": "5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6", "output": ["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]}]
|
control_completion_008510
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w < n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w < n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
Notes: NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Code:
from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List
def solve() -> None:
a = [int(c) % 9 for c in next_token()]
n = len(a)
sa = list(a)
for i in range(1, n):
sa[i] += sa[i - 1]
w = next_int()
indices = defaultdict(list)
for i in range(w, n + 1):
vlr = ((sa[i - 1] - (sa[i - w - 1] if i - w > 0 else 0)) % 9 + 9) % 9
indices[vlr].append(i - w + 1)
cache = dict()
INF = (n + 1, n)
for _ in range(next_int()):
l = next_int() - 1
r = next_int() - 1
k = next_int()
vlr = ((sa[r] - (sa[l - 1] if l > 0 else 0)) % 9 + 9) % 9
if (vlr, k) not in cache:
res = INF
for v1 in range(9):
for v2 in range(9):
if ((v1 * vlr + v2) % 9 + 9) % 9 == k:
if v1 == v2:
if # TODO: Your code here:
res = min(res, tuple(indices[v1][:2]))
else:
if len(indices[v1]) > 0 and len(indices[v2]) > 0:
res = min(res, (indices[v1][0], indices[v2][0]))
cache[(vlr, k)] = res if res != INF else (-1, -1)
print(*cache[(vlr, k)])
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
from __future__ import annotations
import csv
import datetime
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import List
def solve() -> None:
a = [int(c) % 9 for c in next_token()]
n = len(a)
sa = list(a)
for i in range(1, n):
sa[i] += sa[i - 1]
w = next_int()
indices = defaultdict(list)
for i in range(w, n + 1):
vlr = ((sa[i - 1] - (sa[i - w - 1] if i - w > 0 else 0)) % 9 + 9) % 9
indices[vlr].append(i - w + 1)
cache = dict()
INF = (n + 1, n)
for _ in range(next_int()):
l = next_int() - 1
r = next_int() - 1
k = next_int()
vlr = ((sa[r] - (sa[l - 1] if l > 0 else 0)) % 9 + 9) % 9
if (vlr, k) not in cache:
res = INF
for v1 in range(9):
for v2 in range(9):
if ((v1 * vlr + v2) % 9 + 9) % 9 == k:
if v1 == v2:
if {{completion}}:
res = min(res, tuple(indices[v1][:2]))
else:
if len(indices[v1]) > 0 and len(indices[v2]) > 0:
res = min(res, (indices[v1][0], indices[v2][0]))
cache[(vlr, k)] = res if res != INF else (-1, -1)
print(*cache[(vlr, k)])
def global_init() -> None:
pass
RUN_N_TESTS_IN_PROD = True
PRINT_CASE_NUMBER = False
ASSERT_IN_PROD = False
LOG_TO_FILE = False
READ_FROM_CONSOLE_IN_DEBUG = False
WRITE_TO_CONSOLE_IN_DEBUG = True
TEST_TIMER = False
IS_DEBUG = "DEBUG_MODE" in sys.argv
__output_file = None
__input_file = None
__input_last_line = None
def run() -> None:
global __input_file, __input_last_line, __output_file
__output_file = sys.stdout if not IS_DEBUG or WRITE_TO_CONSOLE_IN_DEBUG else open("../output.txt", "w")
try:
__input_file = sys.stdin if not IS_DEBUG or READ_FROM_CONSOLE_IN_DEBUG else open("../input.txt")
try:
with timer("total"):
global_init()
t = next_int() if RUN_N_TESTS_IN_PROD or IS_DEBUG else 1
for i in range(t):
if PRINT_CASE_NUMBER:
fprint(f"Case #{i + 1}: ")
if TEST_TIMER:
with timer(f"test #{i + 1}"):
solve()
else:
solve()
if IS_DEBUG:
__output_file.flush()
finally:
__input_last_line = None
__input_file.close()
__input_file = None
finally:
__output_file.flush()
__output_file.close()
def fprint(*objects, **kwargs):
print(*objects, end="", file=__output_file, **kwargs)
def fprintln(*objects, **kwargs):
print(*objects, file=__output_file, **kwargs)
def next_line() -> str:
global __input_last_line
__input_last_line = None
return __input_file.readline()
def next_token() -> str:
global __input_last_line
while not __input_last_line:
__input_last_line = __input_file.readline().split()[::-1]
return __input_last_line.pop()
def next_int():
return int(next_token())
def next_float():
return float(next_token())
def next_int_array(n: int) -> List[int]:
return [int(next_token()) for _ in range(n)]
if IS_DEBUG or ASSERT_IN_PROD:
def assert_predicate(p: bool, message: str = ""):
if not p:
raise AssertionError(message)
def assert_not_equal(unexpected, actual):
if unexpected == actual:
raise AssertionError(f"assert_not_equal: {unexpected} == {actual}")
def assert_equal(expected, actual):
if expected != actual:
raise AssertionError(f"assert_equal: {expected} != {actual}")
else:
def assert_predicate(p: bool, message: str = ""):
pass
def assert_not_equal(unexpected, actual):
pass
def assert_equal(expected, actual):
pass
if IS_DEBUG:
__log_file = open(f"../logs/py_solution_{int(time.time() * 1000)}.log", "w") if LOG_TO_FILE else sys.stdout
def log(*args, **kwargs):
print(datetime.datetime.now(), "-", *args, **kwargs, flush=True, file=__log_file)
@contextmanager
def timer(label: str):
start_time = time.time()
try:
yield
finally:
log(f"Timer[{label}]: {time.time() - start_time:.6f}s")
else:
def log(*args, **kwargs):
pass
@contextmanager
def timer(label: str):
yield
if __name__ == "__main__":
run()
|
len(indices[v1]) > 1
|
[{"input": "5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6", "output": ["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]}]
|
control_completion_008511
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
# from collections import Counter
"""
standing at point i, why choose to jump to a point j?
if jump:
a*(j-i) + cost(j,n)
if not jump(ie. start from i):
every unconquered kingdom require the distance j-i be conqured, totally n-j times,
-> (j-i)*b*(n-j) + cost(j,n)
compare the two equations:
when a < b*(n-j), we choose to jump to j.
"""
row=lambda:map(int,input().split())
t=int(input())
for _ in range(t):
n,a,b=row()
arr=[0]+list(row())
pos=res=0
for i in range(1,n+1):
d=arr[i]-arr[pos]
res+=b*d
if # TODO: Your code here:
res+=a*d
pos=i
print(res)
|
# from collections import Counter
"""
standing at point i, why choose to jump to a point j?
if jump:
a*(j-i) + cost(j,n)
if not jump(ie. start from i):
every unconquered kingdom require the distance j-i be conqured, totally n-j times,
-> (j-i)*b*(n-j) + cost(j,n)
compare the two equations:
when a < b*(n-j), we choose to jump to j.
"""
row=lambda:map(int,input().split())
t=int(input())
for _ in range(t):
n,a,b=row()
arr=[0]+list(row())
pos=res=0
for i in range(1,n+1):
d=arr[i]-arr[pos]
res+=b*d
if {{completion}}:
res+=a*d
pos=i
print(res)
|
a<b*(n-i)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008534
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def cum_sum(nums):
curr = 0
result = [0]*len(nums)
for # TODO: Your code here:
curr += num
result[idx] = curr
return result
for i in range(1, len(lines), 2):
n, a, b = map(int, lines[i].split(" "))
nums = [0] + list(map(int, lines[i+1].split(" ")))
cumulative = cum_sum(nums)
smallest = float("inf")
for f in range(0, n+1):
curr = a*nums[f]+b*(cumulative[-1] - cumulative[f] - (n-f-1)*nums[f])
smallest = min(curr, smallest)
print(smallest)
|
import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def cum_sum(nums):
curr = 0
result = [0]*len(nums)
for {{completion}}:
curr += num
result[idx] = curr
return result
for i in range(1, len(lines), 2):
n, a, b = map(int, lines[i].split(" "))
nums = [0] + list(map(int, lines[i+1].split(" ")))
cumulative = cum_sum(nums)
smallest = float("inf")
for f in range(0, n+1):
curr = a*nums[f]+b*(cumulative[-1] - cumulative[f] - (n-f-1)*nums[f])
smallest = min(curr, smallest)
print(smallest)
|
idx, num in enumerate(nums)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008535
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def cum_sum(nums):
curr = 0
result = [0]*len(nums)
for idx, num in enumerate(nums):
curr += num
result[idx] = curr
return result
for i in range(1, len(lines), 2):
n, a, b = map(int, lines[i].split(" "))
nums = [0] + list(map(int, lines[i+1].split(" ")))
cumulative = cum_sum(nums)
smallest = float("inf")
for # TODO: Your code here:
curr = a*nums[f]+b*(cumulative[-1] - cumulative[f] - (n-f-1)*nums[f])
smallest = min(curr, smallest)
print(smallest)
|
import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def cum_sum(nums):
curr = 0
result = [0]*len(nums)
for idx, num in enumerate(nums):
curr += num
result[idx] = curr
return result
for i in range(1, len(lines), 2):
n, a, b = map(int, lines[i].split(" "))
nums = [0] + list(map(int, lines[i+1].split(" ")))
cumulative = cum_sum(nums)
smallest = float("inf")
for {{completion}}:
curr = a*nums[f]+b*(cumulative[-1] - cumulative[f] - (n-f-1)*nums[f])
smallest = min(curr, smallest)
print(smallest)
|
f in range(0, n+1)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008536
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
#Name: Codeforces Round #782 (Div. 4)
#Code:
#Rating: 00
#Date: 14/06/2022
#Author: auros25
#Done:
#sys.stdin.readline().strip()
#sys.stdout.write(+"\n")
import sys
#import bisect
for lol in range(int(sys.stdin.readline().strip())):
n, a, b = list(map(int, sys.stdin.readline().strip().split()))
x = list(map(int, sys.stdin.readline().strip().split()))
k = a//b + 1
#print(k)
if # TODO: Your code here:
sys.stdout.write(str(b*(sum(x))) +"\n")
else:
c=a+b
## v=c*x[n-k-1]
## w=k*b*x[n-k-1]
## u= sum(x[n-k:])*b
#print(v, w, u)
#print(v-w+u)
sys.stdout.write( str( c*x[n-k-1] + b*(sum(x[n-k:])-x[n-k-1]*k)) +"\n")
|
#Name: Codeforces Round #782 (Div. 4)
#Code:
#Rating: 00
#Date: 14/06/2022
#Author: auros25
#Done:
#sys.stdin.readline().strip()
#sys.stdout.write(+"\n")
import sys
#import bisect
for lol in range(int(sys.stdin.readline().strip())):
n, a, b = list(map(int, sys.stdin.readline().strip().split()))
x = list(map(int, sys.stdin.readline().strip().split()))
k = a//b + 1
#print(k)
if {{completion}}:
sys.stdout.write(str(b*(sum(x))) +"\n")
else:
c=a+b
## v=c*x[n-k-1]
## w=k*b*x[n-k-1]
## u= sum(x[n-k:])*b
#print(v, w, u)
#print(v-w+u)
sys.stdout.write( str( c*x[n-k-1] + b*(sum(x[n-k:])-x[n-k-1]*k)) +"\n")
|
k >=n
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008537
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
for _ in range(int(input())):
n,a,b=map(int, input().split())
w=[int(x) for x in input().split()]
fb=sum(w)*b
fa=0
ans = fb
cap = 0
cur = n
for x in w:
fb -= x * b
cur -= 1
if # TODO: Your code here:
ans += (x - cap) * a
ans -= (x - cap) * cur * b
cap = x
#print(cap)
print(ans)
|
for _ in range(int(input())):
n,a,b=map(int, input().split())
w=[int(x) for x in input().split()]
fb=sum(w)*b
fa=0
ans = fb
cap = 0
cur = n
for x in w:
fb -= x * b
cur -= 1
if {{completion}}:
ans += (x - cap) * a
ans -= (x - cap) * cur * b
cap = x
#print(cap)
print(ans)
|
(x - cap) * a + fb - (x - cap) * cur * b < fb
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008538
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
t = int(input())
for i in range(t):
li = input().split()
n = int(li[0])
a = int(li[1])
b = int(li[2])
x = input().split()
ans = 0
now = 0
for j in range(n):
ans += b*(int(x[j])-now)
if # TODO: Your code here:
ans += a*(int(x[j])-now)
now = int(x[j])
print(ans)
|
t = int(input())
for i in range(t):
li = input().split()
n = int(li[0])
a = int(li[1])
b = int(li[2])
x = input().split()
ans = 0
now = 0
for j in range(n):
ans += b*(int(x[j])-now)
if {{completion}}:
ans += a*(int(x[j])-now)
now = int(x[j])
print(ans)
|
a < b*(n-j-1)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008539
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
def solve():
n,a,b=map(int,input().split())
xs=list(map(int,input().split()))
cum=0
ans=sum(xs)*b
for # TODO: Your code here:
x=xs[-i-1]
ans=min(ans,x*(a+b)+(cum-x*i)*b)
cum+=x
print(ans)
for _ in range(int(input())):
solve()
|
def solve():
n,a,b=map(int,input().split())
xs=list(map(int,input().split()))
cum=0
ans=sum(xs)*b
for {{completion}}:
x=xs[-i-1]
ans=min(ans,x*(a+b)+(cum-x*i)*b)
cum+=x
print(ans)
for _ in range(int(input())):
solve()
|
i in range(n)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008540
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
t, = I()
for _ in range(t):
n, a, b = I()
x = [0] + I()
suffixes = [0]
for # TODO: Your code here:
move = x[i + 1] - x[i]
tot = suffixes[-1] + len(suffixes) * move * b
suffixes.append(tot)
suffixes = suffixes[::-1]
best = float('inf')
for i in range(n + 1):
best = min(best, x[i] * (b + a) + suffixes[i])
print(best)
|
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
t, = I()
for _ in range(t):
n, a, b = I()
x = [0] + I()
suffixes = [0]
for {{completion}}:
move = x[i + 1] - x[i]
tot = suffixes[-1] + len(suffixes) * move * b
suffixes.append(tot)
suffixes = suffixes[::-1]
best = float('inf')
for i in range(n + 1):
best = min(best, x[i] * (b + a) + suffixes[i])
print(best)
|
i in range(n - 1, -1, -1)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008541
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
t, = I()
for _ in range(t):
n, a, b = I()
x = [0] + I()
suffixes = [0]
for i in range(n - 1, -1, -1):
move = x[i + 1] - x[i]
tot = suffixes[-1] + len(suffixes) * move * b
suffixes.append(tot)
suffixes = suffixes[::-1]
best = float('inf')
for # TODO: Your code here:
best = min(best, x[i] * (b + a) + suffixes[i])
print(best)
|
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
t, = I()
for _ in range(t):
n, a, b = I()
x = [0] + I()
suffixes = [0]
for i in range(n - 1, -1, -1):
move = x[i + 1] - x[i]
tot = suffixes[-1] + len(suffixes) * move * b
suffixes.append(tot)
suffixes = suffixes[::-1]
best = float('inf')
for {{completion}}:
best = min(best, x[i] * (b + a) + suffixes[i])
print(best)
|
i in range(n + 1)
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008542
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you: You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$. From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single integer — the minimum cost to conquer all kingdoms.
Notes: NoteHere is an optimal sequence of moves for the second test case: Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$. Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$. Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$. Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$. Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$. Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$. Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.
Code:
def f(ar,a,b):
ans=0
c=0
n=len(ar)
for id,i in enumerate(ar):
d=i-c
ans+=d*b
if # TODO: Your code here:
ans+=d*a
c=i
return ans
r=lambda :map(int,input().strip().split())
for _ in range(int(input())):
n,a,b=r()
ar=list(r())
print(f(ar,a,b))
|
def f(ar,a,b):
ans=0
c=0
n=len(ar)
for id,i in enumerate(ar):
d=i-c
ans+=d*b
if {{completion}}:
ans+=d*a
c=i
return ans
r=lambda :map(int,input().strip().split())
for _ in range(int(input())):
n,a,b=r()
ar=list(r())
print(f(ar,a,b))
|
d*a<(n-id-1)*(d)*b
|
[{"input": "4\n5 2 7\n3 5 12 13 21\n5 6 3\n1 5 6 21 30\n2 9 3\n10 15\n11 27182 31415\n16 18 33 98 874 989 4848 20458 34365 38117 72030", "output": ["173\n171\n75\n3298918744"]}]
|
control_completion_008543
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
for # TODO: Your code here:n,r,b=map(int,s.split());b+=1;c=r//b*'R'+'B';print((r%b*('R'+c)+n*c)[:n])
|
for {{completion}}:n,r,b=map(int,s.split());b+=1;c=r//b*'R'+'B';print((r%b*('R'+c)+n*c)[:n])
|
s in[*open(0)][1:]
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008556
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
for # TODO: Your code here:
n,r,b=map(int,input().split())
t=((r-1)//(b+1)+1)
k=t*(b+1)-r
res=('R'*t+'B')*(b+1-k)+('R'*(t-1)+'B')*k
print(res[:-1])
#
|
for {{completion}}:
n,r,b=map(int,input().split())
t=((r-1)//(b+1)+1)
k=t*(b+1)-r
res=('R'*t+'B')*(b+1-k)+('R'*(t-1)+'B')*k
print(res[:-1])
#
|
_ in range(int(input()))
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008557
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
tc=int(input())
for # TODO: Your code here:
n,a,b=map(int,input().split());b+=1
print((('R'*(a//b+1)+'B')*(a%b)+('R'*(a//b)+'B')*(b-a%b))[:-1])
|
tc=int(input())
for {{completion}}:
n,a,b=map(int,input().split());b+=1
print((('R'*(a//b+1)+'B')*(a%b)+('R'*(a//b)+'B')*(b-a%b))[:-1])
|
_ in range(tc)
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008558
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
def solve():
n, r, b = list(map(int, input().split(" ")))
d = r // (b+1)
rem = r%(b+1)
s = ''
for i in range(b):
if# TODO: Your code here:
s += 'R'
rem-= 1
s += 'R'*d + 'B'
s += 'R'*d
s+='R'*rem
print(s)
for t in range(int(input())):
solve()
|
def solve():
n, r, b = list(map(int, input().split(" ")))
d = r // (b+1)
rem = r%(b+1)
s = ''
for i in range(b):
if{{completion}}:
s += 'R'
rem-= 1
s += 'R'*d + 'B'
s += 'R'*d
s+='R'*rem
print(s)
for t in range(int(input())):
solve()
|
(rem > 0)
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008559
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
for # TODO: Your code here:n,r,b=map(int,n.split());b+=1;n=r//b*'R';print((r%b*(n+'RB')+(b-r%b)*(n+'B'))[:-1])
|
for {{completion}}:n,r,b=map(int,n.split());b+=1;n=r//b*'R';print((r%b*(n+'RB')+(b-r%b)*(n+'B'))[:-1])
|
n in[*open(0)][1:]
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008560
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
t=int(input())
for # TODO: Your code here:
n,r,b=map(int,input().split())
eq=r//(b+1)
rem=r%(b+1)
print(rem*((eq+1)*"R"+"B")+(b-rem)*(eq*("R")+"B")+eq*"R")
|
t=int(input())
for {{completion}}:
n,r,b=map(int,input().split())
eq=r//(b+1)
rem=r%(b+1)
print(rem*((eq+1)*"R"+"B")+(b-rem)*(eq*("R")+"B")+eq*"R")
|
i in range(0,t)
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008561
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
for t in range(int(input())):
n,r,b = map(int,input().split())
s = []
while r and b:
s.append("R")
s.append("B")
r-=1
b-=1
s.append("R")
r-=1
j = 0
while r:
s[j]+='R'
r-=1
j+=2
if # TODO: Your code here:
j=0
print(*s,sep="")
|
for t in range(int(input())):
n,r,b = map(int,input().split())
s = []
while r and b:
s.append("R")
s.append("B")
r-=1
b-=1
s.append("R")
r-=1
j = 0
while r:
s[j]+='R'
r-=1
j+=2
if {{completion}}:
j=0
print(*s,sep="")
|
j>=len(s)
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008562
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
for # TODO: Your code here:
n,r,b=map(int,l.split())
b+=1
c=(r//b)*'R'+'B'
print(((r%b)*('R'+c)+n*c)[:n])
|
for {{completion}}:
n,r,b=map(int,l.split())
b+=1
c=(r//b)*'R'+'B'
print(((r%b)*('R'+c)+n*c)[:n])
|
l in [*open(0)][1:]
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008563
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
t = int(input())
for i in range(t):
x = input().split()
r = int(x[1])
b = int(x[2])
x = ""
p = r%(b+1)
q = r//(b+1)
for # TODO: Your code here:
x += "R"*(q+1)+"B"
for i in range(b+1-p):
x+= "R"*(q)+"B"
print(x[:-1])
|
t = int(input())
for i in range(t):
x = input().split()
r = int(x[1])
b = int(x[2])
x = ""
p = r%(b+1)
q = r//(b+1)
for {{completion}}:
x += "R"*(q+1)+"B"
for i in range(b+1-p):
x+= "R"*(q)+"B"
print(x[:-1])
|
i in range(p)
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008564
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
t = int(input())
for i in range(t):
x = input().split()
r = int(x[1])
b = int(x[2])
x = ""
p = r%(b+1)
q = r//(b+1)
for i in range(p):
x += "R"*(q+1)+"B"
for # TODO: Your code here:
x+= "R"*(q)+"B"
print(x[:-1])
|
t = int(input())
for i in range(t):
x = input().split()
r = int(x[1])
b = int(x[2])
x = ""
p = r%(b+1)
q = r//(b+1)
for i in range(p):
x += "R"*(q+1)+"B"
for {{completion}}:
x+= "R"*(q)+"B"
print(x[:-1])
|
i in range(b+1-p)
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008565
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
Output Specification: For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
Notes: NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
Code:
for # TODO: Your code here:n,r,b=map(int,n.split());b+=1;print((r%b*('R'*(r//b+1)+'B')+(b-r%b)*(r//b*'R'+'B'))[:-1])
|
for {{completion}}:n,r,b=map(int,n.split());b+=1;print((r%b*('R'*(r//b+1)+'B')+(b-r%b)*(r//b*'R'+'B'))[:-1])
|
n in[*open(0)][1:]
|
[{"input": "3\n7 4 3\n6 5 1\n19 13 6", "output": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR"]}, {"input": "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2", "output": ["RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]}]
|
control_completion_008566
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
for s in[*open(0)][2::2]:
c=[*map(int,s.split())]
a=[1 if x else 0 for x in c]+[1]
for # TODO: Your code here:
a[x+i-i*a[i]]=0
print(*a[:-1])
|
for s in[*open(0)][2::2]:
c=[*map(int,s.split())]
a=[1 if x else 0 for x in c]+[1]
for {{completion}}:
a[x+i-i*a[i]]=0
print(*a[:-1])
|
i,x in enumerate(c)
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008596
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
import sys
def solve():
n = int(input())
num = list(map(int , input().split()))
ret = [1]*n
for i in range(n):
j = num[i]
if # TODO: Your code here:
j += i
if j < n:
ret[j] = 0
print(*ret)
for _ in range(int(input())):
solve()
|
import sys
def solve():
n = int(input())
num = list(map(int , input().split()))
ret = [1]*n
for i in range(n):
j = num[i]
if {{completion}}:
j += i
if j < n:
ret[j] = 0
print(*ret)
for _ in range(int(input())):
solve()
|
j == 0 or ret[i] == 0
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008597
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
import sys
def solve():
n = int(input())
num = list(map(int , input().split()))
ret = [1]*n
for i in range(n):
j = num[i]
if j == 0 or ret[i] == 0:
j += i
if # TODO: Your code here:
ret[j] = 0
print(*ret)
for _ in range(int(input())):
solve()
|
import sys
def solve():
n = int(input())
num = list(map(int , input().split()))
ret = [1]*n
for i in range(n):
j = num[i]
if j == 0 or ret[i] == 0:
j += i
if {{completion}}:
ret[j] = 0
print(*ret)
for _ in range(int(input())):
solve()
|
j < n
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008598
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
t = int(input())
for _ in range(t):
n = int(input())
c = list(map(int, input().split()))
a, e, se, s = [], [0]*n, 0, sum(c)
for # TODO: Your code here:
se -= e[i-1]
n1 = s//i
t = 0 if c[i-1] < i + se else 1
a.append(t)
s -= (n1 + (i-1)*t)
e[i-n1-1] += 1
se += 1
print(*reversed(a))
|
t = int(input())
for _ in range(t):
n = int(input())
c = list(map(int, input().split()))
a, e, se, s = [], [0]*n, 0, sum(c)
for {{completion}}:
se -= e[i-1]
n1 = s//i
t = 0 if c[i-1] < i + se else 1
a.append(t)
s -= (n1 + (i-1)*t)
e[i-n1-1] += 1
se += 1
print(*reversed(a))
|
i in range(n, 0, -1)
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008599
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n, = rl()
c = rl()
a = [1] * n
for i in range(n):
j = c[i]
if # TODO: Your code here:
j += i
if j < n:
a[j] = 0
print(*a)
|
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n, = rl()
c = rl()
a = [1] * n
for i in range(n):
j = c[i]
if {{completion}}:
j += i
if j < n:
a[j] = 0
print(*a)
|
j == 0 or a[i] == 0
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008600
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n, = rl()
c = rl()
a = [1] * n
for i in range(n):
j = c[i]
if j == 0 or a[i] == 0:
j += i
if # TODO: Your code here:
a[j] = 0
print(*a)
|
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n, = rl()
c = rl()
a = [1] * n
for i in range(n):
j = c[i]
if j == 0 or a[i] == 0:
j += i
if {{completion}}:
a[j] = 0
print(*a)
|
j < n
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008601
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
for _ in range(int(input())):
n=int(input())
C=list(map(int,input().split()))
z=sum(C)//n
d=[0]*(n+1)
ans=[]
for i in range(n-1,-1,-1):
d[i]+=d[i+1]
d[i]-=1
d[i-z]+=1
if # TODO: Your code here:
ans.append(1)
z-=1
else:
ans.append(0)
print(*ans[::-1])
|
for _ in range(int(input())):
n=int(input())
C=list(map(int,input().split()))
z=sum(C)//n
d=[0]*(n+1)
ans=[]
for i in range(n-1,-1,-1):
d[i]+=d[i+1]
d[i]-=1
d[i-z]+=1
if {{completion}}:
ans.append(1)
z-=1
else:
ans.append(0)
print(*ans[::-1])
|
z and C[i]+d[i]==i
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008602
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
Notes: NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
Code:
import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
N=int(input())
C=list(map(int,input().split()))
ans=[0]*N
k=sum(C)//N
i=N-1
while i>-1 and k>0:
if # TODO: Your code here:
ans[i]=1
k-=1
else:
C[i-k]+=N-i
i-=1
print(*ans)
|
import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
N=int(input())
C=list(map(int,input().split()))
ans=[0]*N
k=sum(C)//N
i=N-1
while i>-1 and k>0:
if {{completion}}:
ans[i]=1
k-=1
else:
C[i-k]+=N-i
i-=1
print(*ans)
|
C[i]==N
|
[{"input": "5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3", "output": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]}]
|
control_completion_008603
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
Output Specification: For each query, print one line containing a single integer — the answer to the query.
Notes: NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
Code:
import sys
input = sys.stdin.readline
class DSU:
def __init__(self, n):
self.UF = list(range(n))
self.sz = [0]*n
def find(self, u):
UF = self.UF
if UF[u]!=u:
UF[u] = self.find(UF[u])
return UF[u]
def union(self,u,v):
UF = self.UF
sz = self.sz
pu = self.find(u)
pv = self.find(v)
if pu == pv:
return False
if sz[pu] >= sz[pv]:
sz[pu] += 1
UF[pv] = pu
else:
sz[pv] += 1
UF[pu] = pv
return True
n,m = map(int,input().split())
good = []
DSUs = [DSU(n+1) for _ in range(30)]
for _ in range(m):
u,v,w = map(int,input().split())
u -= 1
v -= 1
if w%2 == 0:
good.append((u,v,w))
for k in range(0, 30):
if # TODO: Your code here:
DSUs[k].union(u,v)
q = int(input())
Q = [None]*q
ans = [2]*q
for i in range(q):
u,v = map(int,input().split())
u -= 1
v -= 1
Q[i] = u,v
for k in range(0, 30):
if DSUs[k].find(u) == DSUs[k].find(v):
ans[i] = 0
break
for u,v,w in good:
for k in range(1, 30):
DSUs[k].union(u, n)
DSUs[k].union(v, n)
for i in range(q):
if ans[i] == 0:
continue
u,v = Q[i]
for k in range(1, 30):
if DSUs[k].find(u) == DSUs[k].find(n):
ans[i] = 1
break
print("\n".join(str(x) for x in ans))
|
import sys
input = sys.stdin.readline
class DSU:
def __init__(self, n):
self.UF = list(range(n))
self.sz = [0]*n
def find(self, u):
UF = self.UF
if UF[u]!=u:
UF[u] = self.find(UF[u])
return UF[u]
def union(self,u,v):
UF = self.UF
sz = self.sz
pu = self.find(u)
pv = self.find(v)
if pu == pv:
return False
if sz[pu] >= sz[pv]:
sz[pu] += 1
UF[pv] = pu
else:
sz[pv] += 1
UF[pu] = pv
return True
n,m = map(int,input().split())
good = []
DSUs = [DSU(n+1) for _ in range(30)]
for _ in range(m):
u,v,w = map(int,input().split())
u -= 1
v -= 1
if w%2 == 0:
good.append((u,v,w))
for k in range(0, 30):
if {{completion}}:
DSUs[k].union(u,v)
q = int(input())
Q = [None]*q
ans = [2]*q
for i in range(q):
u,v = map(int,input().split())
u -= 1
v -= 1
Q[i] = u,v
for k in range(0, 30):
if DSUs[k].find(u) == DSUs[k].find(v):
ans[i] = 0
break
for u,v,w in good:
for k in range(1, 30):
DSUs[k].union(u, n)
DSUs[k].union(v, n)
for i in range(q):
if ans[i] == 0:
continue
u,v = Q[i]
for k in range(1, 30):
if DSUs[k].find(u) == DSUs[k].find(n):
ans[i] = 1
break
print("\n".join(str(x) for x in ans))
|
w & (1<<k)
|
[{"input": "6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "output": ["2\n0\n1"]}, {"input": "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8", "output": ["0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]}]
|
control_completion_008615
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
Output Specification: For each query, print one line containing a single integer — the answer to the query.
Notes: NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
Code:
import sys
input = sys.stdin.readline
class DSU:
def __init__(self, n):
self.UF = list(range(n))
self.sz = [0]*n
def find(self, u):
UF = self.UF
if UF[u]!=u:
UF[u] = self.find(UF[u])
return UF[u]
def union(self,u,v):
UF = self.UF
sz = self.sz
pu = self.find(u)
pv = self.find(v)
if pu == pv:
return False
if sz[pu] >= sz[pv]:
sz[pu] += 1
UF[pv] = pu
else:
sz[pv] += 1
UF[pu] = pv
return True
n,m = map(int,input().split())
good = []
DSUs = [DSU(n+1) for _ in range(30)]
for _ in range(m):
u,v,w = map(int,input().split())
u -= 1
v -= 1
if w%2 == 0:
good.append((u,v,w))
for k in range(0, 30):
if w & (1<<k):
DSUs[k].union(u,v)
q = int(input())
Q = [None]*q
ans = [2]*q
for i in range(q):
u,v = map(int,input().split())
u -= 1
v -= 1
Q[i] = u,v
for k in range(0, 30):
if # TODO: Your code here:
ans[i] = 0
break
for u,v,w in good:
for k in range(1, 30):
DSUs[k].union(u, n)
DSUs[k].union(v, n)
for i in range(q):
if ans[i] == 0:
continue
u,v = Q[i]
for k in range(1, 30):
if DSUs[k].find(u) == DSUs[k].find(n):
ans[i] = 1
break
print("\n".join(str(x) for x in ans))
|
import sys
input = sys.stdin.readline
class DSU:
def __init__(self, n):
self.UF = list(range(n))
self.sz = [0]*n
def find(self, u):
UF = self.UF
if UF[u]!=u:
UF[u] = self.find(UF[u])
return UF[u]
def union(self,u,v):
UF = self.UF
sz = self.sz
pu = self.find(u)
pv = self.find(v)
if pu == pv:
return False
if sz[pu] >= sz[pv]:
sz[pu] += 1
UF[pv] = pu
else:
sz[pv] += 1
UF[pu] = pv
return True
n,m = map(int,input().split())
good = []
DSUs = [DSU(n+1) for _ in range(30)]
for _ in range(m):
u,v,w = map(int,input().split())
u -= 1
v -= 1
if w%2 == 0:
good.append((u,v,w))
for k in range(0, 30):
if w & (1<<k):
DSUs[k].union(u,v)
q = int(input())
Q = [None]*q
ans = [2]*q
for i in range(q):
u,v = map(int,input().split())
u -= 1
v -= 1
Q[i] = u,v
for k in range(0, 30):
if {{completion}}:
ans[i] = 0
break
for u,v,w in good:
for k in range(1, 30):
DSUs[k].union(u, n)
DSUs[k].union(v, n)
for i in range(q):
if ans[i] == 0:
continue
u,v = Q[i]
for k in range(1, 30):
if DSUs[k].find(u) == DSUs[k].find(n):
ans[i] = 1
break
print("\n".join(str(x) for x in ans))
|
DSUs[k].find(u) == DSUs[k].find(v)
|
[{"input": "6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "output": ["2\n0\n1"]}, {"input": "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8", "output": ["0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]}]
|
control_completion_008616
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
Output Specification: For each query, print one line containing a single integer — the answer to the query.
Notes: NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
Code:
import sys
input = sys.stdin.readline
def bit(w, b):
if w & (1 << b):
return 1
return 0
class DSU:
def __init__(self, n):
self.n = n
self.parent = [i for i in range(self.n)]
self.SZ = [1 for _ in range(self.n)]
def root(self, node):
if self.parent[node] == node:
return node
self.parent[node] = self.root(self.parent[node])
return self.parent[node]
def merge(self, u, v):
u = self.root(u)
v = self.root(v)
if u == v:
return
if self.SZ[u] < self.SZ[v]:
temp = u
u = v
v = temp
self.parent[v] = u
self.SZ[u] += self.SZ[v]
class Solver1659E:
def __init__(self):
self.C = 30
self.n, self.m = list(map(int, input().split(' ')))
self.bit_i = [DSU(self.n) for _ in range(self.C)]
self.bit_i_0 = [DSU(self.n) for _ in range(self.C)]
self.one_works = [[0 for _ in range(self.n)] for _ in range(self.C)]
for i in range(self.m):
u, v, w = list(map(int, input().split(' ')))
u -= 1
v -= 1
for j in range(self.C):
if # TODO: Your code here:
self.bit_i[j].merge(u, v)
if bit(w, j) and bit(w, 0):
self.bit_i_0[j].merge(u, v)
if bit(w, 0) == 0:
self.one_works[j][u] = 1
self.one_works[j][v] = 1
for b in range(self.C):
for i in range(self.n):
if self.one_works[b][i] == 1:
self.one_works[b][self.bit_i_0[b].root(i)] = 1
#print(self.one_works)
def query(self):
u, v = list(map(int, input().split(' ')))
u -= 1
v -= 1
for b in range(self.C):
if self.bit_i[b].root(u) == self.bit_i[b].root(v):
return 0
for b in range(1, self.C):
if self.bit_i_0[b].root(u) == self.bit_i_0[b].root(v):
#print("i_0=",b)
return 1
if self.one_works[b][self.bit_i_0[b].root(u)]:
#print("one_works=",b,self.bit_i_0[b].root(u))
return 1
return 2
cur = Solver1659E()
q = int(input())
while q:
q -= 1
print(cur.query())
|
import sys
input = sys.stdin.readline
def bit(w, b):
if w & (1 << b):
return 1
return 0
class DSU:
def __init__(self, n):
self.n = n
self.parent = [i for i in range(self.n)]
self.SZ = [1 for _ in range(self.n)]
def root(self, node):
if self.parent[node] == node:
return node
self.parent[node] = self.root(self.parent[node])
return self.parent[node]
def merge(self, u, v):
u = self.root(u)
v = self.root(v)
if u == v:
return
if self.SZ[u] < self.SZ[v]:
temp = u
u = v
v = temp
self.parent[v] = u
self.SZ[u] += self.SZ[v]
class Solver1659E:
def __init__(self):
self.C = 30
self.n, self.m = list(map(int, input().split(' ')))
self.bit_i = [DSU(self.n) for _ in range(self.C)]
self.bit_i_0 = [DSU(self.n) for _ in range(self.C)]
self.one_works = [[0 for _ in range(self.n)] for _ in range(self.C)]
for i in range(self.m):
u, v, w = list(map(int, input().split(' ')))
u -= 1
v -= 1
for j in range(self.C):
if {{completion}}:
self.bit_i[j].merge(u, v)
if bit(w, j) and bit(w, 0):
self.bit_i_0[j].merge(u, v)
if bit(w, 0) == 0:
self.one_works[j][u] = 1
self.one_works[j][v] = 1
for b in range(self.C):
for i in range(self.n):
if self.one_works[b][i] == 1:
self.one_works[b][self.bit_i_0[b].root(i)] = 1
#print(self.one_works)
def query(self):
u, v = list(map(int, input().split(' ')))
u -= 1
v -= 1
for b in range(self.C):
if self.bit_i[b].root(u) == self.bit_i[b].root(v):
return 0
for b in range(1, self.C):
if self.bit_i_0[b].root(u) == self.bit_i_0[b].root(v):
#print("i_0=",b)
return 1
if self.one_works[b][self.bit_i_0[b].root(u)]:
#print("one_works=",b,self.bit_i_0[b].root(u))
return 1
return 2
cur = Solver1659E()
q = int(input())
while q:
q -= 1
print(cur.query())
|
bit(w, j)
|
[{"input": "6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "output": ["2\n0\n1"]}, {"input": "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8", "output": ["0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]}]
|
control_completion_008617
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
Output Specification: For each query, print one line containing a single integer — the answer to the query.
Notes: NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
Code:
import sys
input = sys.stdin.readline
def bit(w, b):
if w & (1 << b):
return 1
return 0
class DSU:
def __init__(self, n):
self.n = n
self.parent = [i for i in range(self.n)]
self.SZ = [1 for _ in range(self.n)]
def root(self, node):
if self.parent[node] == node:
return node
self.parent[node] = self.root(self.parent[node])
return self.parent[node]
def merge(self, u, v):
u = self.root(u)
v = self.root(v)
if u == v:
return
if self.SZ[u] < self.SZ[v]:
temp = u
u = v
v = temp
self.parent[v] = u
self.SZ[u] += self.SZ[v]
class Solver1659E:
def __init__(self):
self.C = 30
self.n, self.m = list(map(int, input().split(' ')))
self.bit_i = [DSU(self.n) for _ in range(self.C)]
self.bit_i_0 = [DSU(self.n) for _ in range(self.C)]
self.one_works = [[0 for _ in range(self.n)] for _ in range(self.C)]
for i in range(self.m):
u, v, w = list(map(int, input().split(' ')))
u -= 1
v -= 1
for j in range(self.C):
if bit(w, j):
self.bit_i[j].merge(u, v)
if # TODO: Your code here:
self.bit_i_0[j].merge(u, v)
if bit(w, 0) == 0:
self.one_works[j][u] = 1
self.one_works[j][v] = 1
for b in range(self.C):
for i in range(self.n):
if self.one_works[b][i] == 1:
self.one_works[b][self.bit_i_0[b].root(i)] = 1
#print(self.one_works)
def query(self):
u, v = list(map(int, input().split(' ')))
u -= 1
v -= 1
for b in range(self.C):
if self.bit_i[b].root(u) == self.bit_i[b].root(v):
return 0
for b in range(1, self.C):
if self.bit_i_0[b].root(u) == self.bit_i_0[b].root(v):
#print("i_0=",b)
return 1
if self.one_works[b][self.bit_i_0[b].root(u)]:
#print("one_works=",b,self.bit_i_0[b].root(u))
return 1
return 2
cur = Solver1659E()
q = int(input())
while q:
q -= 1
print(cur.query())
|
import sys
input = sys.stdin.readline
def bit(w, b):
if w & (1 << b):
return 1
return 0
class DSU:
def __init__(self, n):
self.n = n
self.parent = [i for i in range(self.n)]
self.SZ = [1 for _ in range(self.n)]
def root(self, node):
if self.parent[node] == node:
return node
self.parent[node] = self.root(self.parent[node])
return self.parent[node]
def merge(self, u, v):
u = self.root(u)
v = self.root(v)
if u == v:
return
if self.SZ[u] < self.SZ[v]:
temp = u
u = v
v = temp
self.parent[v] = u
self.SZ[u] += self.SZ[v]
class Solver1659E:
def __init__(self):
self.C = 30
self.n, self.m = list(map(int, input().split(' ')))
self.bit_i = [DSU(self.n) for _ in range(self.C)]
self.bit_i_0 = [DSU(self.n) for _ in range(self.C)]
self.one_works = [[0 for _ in range(self.n)] for _ in range(self.C)]
for i in range(self.m):
u, v, w = list(map(int, input().split(' ')))
u -= 1
v -= 1
for j in range(self.C):
if bit(w, j):
self.bit_i[j].merge(u, v)
if {{completion}}:
self.bit_i_0[j].merge(u, v)
if bit(w, 0) == 0:
self.one_works[j][u] = 1
self.one_works[j][v] = 1
for b in range(self.C):
for i in range(self.n):
if self.one_works[b][i] == 1:
self.one_works[b][self.bit_i_0[b].root(i)] = 1
#print(self.one_works)
def query(self):
u, v = list(map(int, input().split(' ')))
u -= 1
v -= 1
for b in range(self.C):
if self.bit_i[b].root(u) == self.bit_i[b].root(v):
return 0
for b in range(1, self.C):
if self.bit_i_0[b].root(u) == self.bit_i_0[b].root(v):
#print("i_0=",b)
return 1
if self.one_works[b][self.bit_i_0[b].root(u)]:
#print("one_works=",b,self.bit_i_0[b].root(u))
return 1
return 2
cur = Solver1659E()
q = int(input())
while q:
q -= 1
print(cur.query())
|
bit(w, j) and bit(w, 0)
|
[{"input": "6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "output": ["2\n0\n1"]}, {"input": "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8", "output": ["0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]}]
|
control_completion_008618
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
Output Specification: For each query, print one line containing a single integer — the answer to the query.
Notes: NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
Code:
from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
class dsu:
def __init__(self , n):
self.p = [0]*(n + 1)
self.rank = [0]*(n + 1)
for i in range(1 , n + 1):
self.p[i] = i
def find(self , node):
if(self.p[node] == node):return node
self.p[node] = self.find(self.p[node])
return self.p[node]
def union(self , u , v):
u , v = self.find(u) , self.find(v)
if(self.rank[u] == self.rank[v]):
self.p[v] = u
self.rank[u] += 1
elif(self.rank[u] > self.rank[v]):
self.p[v] = u
else:
self.p[u] = v
def answer():
zeronotset = [False for i in range(n + 1)]
for i in range(m):
u , v , w = edges[i]
if(w & 1 == 0):
zeronotset[u] = True
zeronotset[v] = True
d = [dsu(n) for i in range(30)]
for i in range(30):
for j in range(m):
u , v , w = edges[j]
if(w >> i & 1):
d[i].union(u , v)
zero = [dsu(n) for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(w & 1 and w >> i & 1):
zero[i].union(u , v)
value = [[2 for i in range(n + 1)] for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(zeronotset[u]):
value[i][zero[i].find(u)] = 1
if(zeronotset[v]):
value[i][zero[i].find(v)] = 1
for q in range(int(input())):
u , v = inp()
ans = 2
for i in range(30):
if(d[i].find(u) == d[i].find(v)):
ans = 0
break
if(ans == 2):
for i in range(1 , 30):
if# TODO: Your code here:
ans = 1
break
print(ans)
for T in range(1):
n , m = inp()
edges = []
for i in range(m):
u , v , w = inp()
edges.append([u , v , w])
answer()
|
from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
class dsu:
def __init__(self , n):
self.p = [0]*(n + 1)
self.rank = [0]*(n + 1)
for i in range(1 , n + 1):
self.p[i] = i
def find(self , node):
if(self.p[node] == node):return node
self.p[node] = self.find(self.p[node])
return self.p[node]
def union(self , u , v):
u , v = self.find(u) , self.find(v)
if(self.rank[u] == self.rank[v]):
self.p[v] = u
self.rank[u] += 1
elif(self.rank[u] > self.rank[v]):
self.p[v] = u
else:
self.p[u] = v
def answer():
zeronotset = [False for i in range(n + 1)]
for i in range(m):
u , v , w = edges[i]
if(w & 1 == 0):
zeronotset[u] = True
zeronotset[v] = True
d = [dsu(n) for i in range(30)]
for i in range(30):
for j in range(m):
u , v , w = edges[j]
if(w >> i & 1):
d[i].union(u , v)
zero = [dsu(n) for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(w & 1 and w >> i & 1):
zero[i].union(u , v)
value = [[2 for i in range(n + 1)] for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(zeronotset[u]):
value[i][zero[i].find(u)] = 1
if(zeronotset[v]):
value[i][zero[i].find(v)] = 1
for q in range(int(input())):
u , v = inp()
ans = 2
for i in range(30):
if(d[i].find(u) == d[i].find(v)):
ans = 0
break
if(ans == 2):
for i in range(1 , 30):
if{{completion}}:
ans = 1
break
print(ans)
for T in range(1):
n , m = inp()
edges = []
for i in range(m):
u , v , w = inp()
edges.append([u , v , w])
answer()
|
(value[i][zero[i].find(u)] == 1)
|
[{"input": "6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "output": ["2\n0\n1"]}, {"input": "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8", "output": ["0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]}]
|
control_completion_008619
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
Output Specification: For each query, print one line containing a single integer — the answer to the query.
Notes: NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
Code:
from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
class dsu:
def __init__(self , n):
self.p = [0]*(n + 1)
self.rank = [0]*(n + 1)
for i in range(1 , n + 1):
self.p[i] = i
def find(self , node):
if(self.p[node] == node):return node
self.p[node] = self.find(self.p[node])
return self.p[node]
def union(self , u , v):
u , v = self.find(u) , self.find(v)
if(self.rank[u] == self.rank[v]):
self.p[v] = u
self.rank[u] += 1
elif(self.rank[u] > self.rank[v]):
self.p[v] = u
else:
self.p[u] = v
def answer():
zeronotset = [False for i in range(n + 1)]
for i in range(m):
u , v , w = edges[i]
if(w & 1 == 0):
zeronotset[u] = True
zeronotset[v] = True
d = [dsu(n) for i in range(30)]
for i in range(30):
for j in range(m):
u , v , w = edges[j]
if# TODO: Your code here:
d[i].union(u , v)
zero = [dsu(n) for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(w & 1 and w >> i & 1):
zero[i].union(u , v)
value = [[2 for i in range(n + 1)] for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(zeronotset[u]):
value[i][zero[i].find(u)] = 1
if(zeronotset[v]):
value[i][zero[i].find(v)] = 1
for q in range(int(input())):
u , v = inp()
ans = 2
for i in range(30):
if(d[i].find(u) == d[i].find(v)):
ans = 0
break
if(ans == 2):
for i in range(1 , 30):
if(value[i][zero[i].find(u)] == 1):
ans = 1
break
print(ans)
for T in range(1):
n , m = inp()
edges = []
for i in range(m):
u , v , w = inp()
edges.append([u , v , w])
answer()
|
from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
class dsu:
def __init__(self , n):
self.p = [0]*(n + 1)
self.rank = [0]*(n + 1)
for i in range(1 , n + 1):
self.p[i] = i
def find(self , node):
if(self.p[node] == node):return node
self.p[node] = self.find(self.p[node])
return self.p[node]
def union(self , u , v):
u , v = self.find(u) , self.find(v)
if(self.rank[u] == self.rank[v]):
self.p[v] = u
self.rank[u] += 1
elif(self.rank[u] > self.rank[v]):
self.p[v] = u
else:
self.p[u] = v
def answer():
zeronotset = [False for i in range(n + 1)]
for i in range(m):
u , v , w = edges[i]
if(w & 1 == 0):
zeronotset[u] = True
zeronotset[v] = True
d = [dsu(n) for i in range(30)]
for i in range(30):
for j in range(m):
u , v , w = edges[j]
if{{completion}}:
d[i].union(u , v)
zero = [dsu(n) for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(w & 1 and w >> i & 1):
zero[i].union(u , v)
value = [[2 for i in range(n + 1)] for i in range(30)]
for i in range(1 , 30):
for j in range(m):
u , v , w = edges[j]
if(zeronotset[u]):
value[i][zero[i].find(u)] = 1
if(zeronotset[v]):
value[i][zero[i].find(v)] = 1
for q in range(int(input())):
u , v = inp()
ans = 2
for i in range(30):
if(d[i].find(u) == d[i].find(v)):
ans = 0
break
if(ans == 2):
for i in range(1 , 30):
if(value[i][zero[i].find(u)] == 1):
ans = 1
break
print(ans)
for T in range(1):
n , m = inp()
edges = []
for i in range(m):
u , v , w = inp()
edges.append([u , v , w])
answer()
|
(w >> i & 1)
|
[{"input": "6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "output": ["2\n0\n1"]}, {"input": "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8", "output": ["0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]}]
|
control_completion_008620
|
control_fixed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.