lang
stringclasses 1
value | prompt
stringlengths 1.38k
11.3k
| eval_prompt
stringlengths 39
8.09k
| ground_truth
stringlengths 3
196
| unit_tests
stringlengths 44
873
| task_id
stringlengths 23
25
| split
stringclasses 2
values |
---|---|---|---|---|---|---|
python
|
Complete the code in python to solve this programming problem:
Description: Codeforces separates its users into $$$4$$$ divisions by their rating: For Division 1: $$$1900 \leq \mathrm{rating}$$$ For Division 2: $$$1600 \leq \mathrm{rating} \leq 1899$$$ For Division 3: $$$1400 \leq \mathrm{rating} \leq 1599$$$ For Division 4: $$$\mathrm{rating} \leq 1399$$$ Given a $$$\mathrm{rating}$$$, print in which division the $$$\mathrm{rating}$$$ belongs.
Input Specification: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of testcases. The description of each test consists of one line containing one integer $$$\mathrm{rating}$$$ ($$$-5000 \leq \mathrm{rating} \leq 5000$$$).
Output Specification: For each test case, output a single line containing the correct division in the format "Division X", where $$$X$$$ is an integer between $$$1$$$ and $$$4$$$ representing the division for the corresponding rating.
Notes: NoteFor test cases $$$1-4$$$, the corresponding ratings are $$$-789$$$, $$$1299$$$, $$$1300$$$, $$$1399$$$, so all of them are in division $$$4$$$.For the fifth test case, the corresponding rating is $$$1400$$$, so it is in division $$$3$$$.For the sixth test case, the corresponding rating is $$$1679$$$, so it is in division $$$2$$$.For the seventh test case, the corresponding rating is $$$2300$$$, so it is in division $$$1$$$.
Code:
def div(n):
# TODO: Your code here
for _ in range(int(input())):
print(f'Division {div(int(input()))}')
|
def div(n):
{{completion}}
for _ in range(int(input())):
print(f'Division {div(int(input()))}')
|
return 1 if n >= 1900 else 2 if n >= 1600 else 3 if n >= 1400 else 4
|
[{"input": "7\n-789\n1299\n1300\n1399\n1400\n1679\n2300", "output": ["Division 4\nDivision 4\nDivision 4\nDivision 4\nDivision 3\nDivision 2\nDivision 1"]}]
|
block_completion_000729
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$) — the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$) — it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integer — the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
# TODO: Your code here
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
continue
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
{{completion}}
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
continue
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
continue
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005667
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is the easy version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1'($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good?
Input Specification: The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print a single line with one integer — the minimum number of operations to make $$$s$$$ good.
Notes: NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100".In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.
Code:
t=int(input(""))
for z in range(t):
n=int(input(""))
a=input("")
s=[]
for i in range(0,len(a)-1,2):
# TODO: Your code here
b=s.count('10')
c=s.count('01')
print(b+c)
|
t=int(input(""))
for z in range(t):
n=int(input(""))
a=input("")
s=[]
for i in range(0,len(a)-1,2):
{{completion}}
b=s.count('10')
c=s.count('01')
print(b+c)
|
ab=a[i]+a[i+1]
s.append(ab)
|
[{"input": "5\n10\n1110011000\n8\n11001111\n2\n00\n2\n11\n6\n100110", "output": ["3\n0\n0\n0\n3"]}]
|
block_completion_008121
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
def solve():
# Size of the matrices.
n = int(input())
# Data matrix (the first two rows correspond to the original matrix
# and the last two to the target matrix).
matrix = []
# Read the input data.
for _ in range(4):
matrix.append([int(data) for data in input().split()])
top = 0 # Difference between the prefixes of the first rows of the matrices.
bottom = 0 # Difference between the prefixes of the second rows of the matrices.
total = 0 # Total cost of the operations.
for i in range(n):
top += (matrix[0][i] - matrix[2][i]) # Update the first prefix.
bottom += (matrix[1][i] - matrix[3][i]) # Update the second prefix.
# If the prefix differences have different signs, swap the exceeding one
# in the positive row to the negative, spending an operation on it.
if bottom < 0 and 0 < top:
top -= 1
bottom += 1
total += 1
elif # TODO: Your code here:
top += 1
bottom -= 1
total += 1
# Update the total cost with the cost of fixing this prefix, since the last fix.
total += abs(top) + abs(bottom)
# The condition top + bottom == 0 is equivalent to top == 0 && bottom == 0, because top and
# bottom always have the same sign or at least one is zero.
# Therefore, if top + bottom != 0, then top != 0 or bottom != 0.
# This mean the matrices have different amount of one, so the problem is unsolvable.
if top + bottom != 0:
return -1
# Otherwise, the problem has a solution, and it's the total calculated cost.
return total
print(solve())
|
def solve():
# Size of the matrices.
n = int(input())
# Data matrix (the first two rows correspond to the original matrix
# and the last two to the target matrix).
matrix = []
# Read the input data.
for _ in range(4):
matrix.append([int(data) for data in input().split()])
top = 0 # Difference between the prefixes of the first rows of the matrices.
bottom = 0 # Difference between the prefixes of the second rows of the matrices.
total = 0 # Total cost of the operations.
for i in range(n):
top += (matrix[0][i] - matrix[2][i]) # Update the first prefix.
bottom += (matrix[1][i] - matrix[3][i]) # Update the second prefix.
# If the prefix differences have different signs, swap the exceeding one
# in the positive row to the negative, spending an operation on it.
if bottom < 0 and 0 < top:
top -= 1
bottom += 1
total += 1
elif {{completion}}:
top += 1
bottom -= 1
total += 1
# Update the total cost with the cost of fixing this prefix, since the last fix.
total += abs(top) + abs(bottom)
# The condition top + bottom == 0 is equivalent to top == 0 && bottom == 0, because top and
# bottom always have the same sign or at least one is zero.
# Therefore, if top + bottom != 0, then top != 0 or bottom != 0.
# This mean the matrices have different amount of one, so the problem is unsolvable.
if top + bottom != 0:
return -1
# Otherwise, the problem has a solution, and it's the total calculated cost.
return total
print(solve())
|
top < 0 and 0 < bottom
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
control_completion_004174
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can: Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.
Input Specification: The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).
Output Specification: For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.
Notes: NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$. During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$; during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.
Code:
from bisect import bisect
t = int(input().strip())
def solve(o, t):
if t - o > 1:
d = (t - o) // 3 + ((t - o) % 3 == 2)
o, t = o + 2 * d, t - d
return (o + (t > o)) * 2 - (o > t)
out = []
for _ in range(t):
n = int(input().strip())
h = list(map(int, input().strip().split()))
mx = max(h)
o, t, e = 0, 0, 0
for x in h:
# TODO: Your code here
out.append(str(min(solve(o, t), solve(e, t + o))))
print("\n".join(out))
|
from bisect import bisect
t = int(input().strip())
def solve(o, t):
if t - o > 1:
d = (t - o) // 3 + ((t - o) % 3 == 2)
o, t = o + 2 * d, t - d
return (o + (t > o)) * 2 - (o > t)
out = []
for _ in range(t):
n = int(input().strip())
h = list(map(int, input().strip().split()))
mx = max(h)
o, t, e = 0, 0, 0
for x in h:
{{completion}}
out.append(str(min(solve(o, t), solve(e, t + o))))
print("\n".join(out))
|
e += (mx - x + 1) % 2
o += (mx - x) % 2
t += (mx - x) // 2
|
[{"input": "3\n3\n1 2 4\n5\n4 4 3 5 5\n7\n2 5 4 8 3 7 4", "output": ["4\n3\n16"]}]
|
block_completion_003417
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
Output Specification: Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
Notes: NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
Code:
input = __import__('sys').stdin.readline
n = int(input())
a = list(map(int, input().split())) + [n+1]
ans = 0
cache = {}
for i in range(n):
u = 0
d = n+1
keys = []
j = i
while j+1 <= n:
key = (j, u, d)
v = cache.get(key, -1)
if v != -1:
j = v
break
keys.append(key)
# greedy
if u < a[j] < d: # if can insert to both
if a[j] < a[j+1]:
u = max(u, a[j])
elif a[j] > a[j+1]:
# TODO: Your code here
elif u < a[j]: # if only can insert to increasing subsequence
u = a[j]
elif d > a[j]: # if only can insert to decreasing subsequence
d = a[j]
else:
break
j += 1
for key in keys:
cache[key] = j
ans += j - i
# print(f'at {i} max {j} ans {ans}', u, d)
# print(f'count={len(cache)}')
print(ans)
|
input = __import__('sys').stdin.readline
n = int(input())
a = list(map(int, input().split())) + [n+1]
ans = 0
cache = {}
for i in range(n):
u = 0
d = n+1
keys = []
j = i
while j+1 <= n:
key = (j, u, d)
v = cache.get(key, -1)
if v != -1:
j = v
break
keys.append(key)
# greedy
if u < a[j] < d: # if can insert to both
if a[j] < a[j+1]:
u = max(u, a[j])
elif a[j] > a[j+1]:
{{completion}}
elif u < a[j]: # if only can insert to increasing subsequence
u = a[j]
elif d > a[j]: # if only can insert to decreasing subsequence
d = a[j]
else:
break
j += 1
for key in keys:
cache[key] = j
ans += j - i
# print(f'at {i} max {j} ans {ans}', u, d)
# print(f'count={len(cache)}')
print(ans)
|
d = min(d, a[j])
|
[{"input": "3\n2 3 1", "output": ["6"]}, {"input": "6\n4 5 2 6 1 3", "output": ["19"]}, {"input": "10\n7 10 1 8 3 9 2 4 6 5", "output": ["39"]}]
|
block_completion_000487
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ of $$$n$$$ integers. Initially there is only one copy of the given array.You can do operations of two types: Choose any array and clone it. After that there is one more copy of the chosen array. Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case output a single integer — the minimal number of operations needed to create at least one copy where all elements are equal.
Notes: NoteIn the first test case all elements in the array are already equal, that's why the answer is $$$0$$$.In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:$$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$After that we can swap elements in a way so all zeroes are in one array:$$$[ \ 0 \ \underline{0} \ \underline{0} \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ \underline{1} \ 1 \ 3 \ 3 \ 7 \ \underline{3} \ ]$$$Now let's create a copy of the first array:$$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$, $$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$Let's swap elements in the first two copies:$$$[ \ 0 \ 0 \ 0 \ \underline{0} \ \underline{0} \ 0 \ ]$$$, $$$[ \ \underline{3} \ \underline{7} \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$.Finally, we made a copy where all elements are equal and made $$$6$$$ operations.It can be proven that no fewer operations are enough.
Code:
from collections import Counter
def solve():
n = int(input())
freq = max(Counter(input().split()).values())
left = n - freq
ans=0
while# TODO: Your code here:
ans += 1+min(left,freq)
left = left - min(left,freq)
freq=2*freq
print(ans)
while(True):
try:
test = int(input())
except EOFError:
break
for i in range (test):
solve()
|
from collections import Counter
def solve():
n = int(input())
freq = max(Counter(input().split()).values())
left = n - freq
ans=0
while{{completion}}:
ans += 1+min(left,freq)
left = left - min(left,freq)
freq=2*freq
print(ans)
while(True):
try:
test = int(input())
except EOFError:
break
for i in range (test):
solve()
|
(left)
|
[{"input": "6\n1\n1789\n6\n0 1 3 3 7 0\n2\n-1000000000 1000000000\n4\n4 3 2 1\n5\n2 5 7 6 3\n7\n1 1 1 1 1 1 1", "output": ["0\n6\n2\n5\n7\n0"]}]
|
control_completion_004340
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can: Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.
Input Specification: The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).
Output Specification: For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.
Notes: NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$. During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$; during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.
Code:
for ii in range(int(input())):
n=int(input())
a = list(map(int, input().split()))
m=max(a)
ans=float("inf")
for jj in range(m,m+4):
x,y=0,0
for # TODO: Your code here:
x+=(jj-kk)%2
y+=(jj-kk)//2
ans=min(max(((x+y*2)//3*2)+(x+y*2)%3,x*2-1),ans)
print(ans)
|
for ii in range(int(input())):
n=int(input())
a = list(map(int, input().split()))
m=max(a)
ans=float("inf")
for jj in range(m,m+4):
x,y=0,0
for {{completion}}:
x+=(jj-kk)%2
y+=(jj-kk)//2
ans=min(max(((x+y*2)//3*2)+(x+y*2)%3,x*2-1),ans)
print(ans)
|
kk in a
|
[{"input": "3\n3\n1 2 4\n5\n4 4 3 5 5\n7\n2 5 4 8 3 7 4", "output": ["4\n3\n16"]}]
|
control_completion_003368
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
for i in range(int(input())):
n= int(input())
a = dict()
b = dict()
c = dict()
ans = 0
for j in range(n):
d,e = str(input())
try:
ans += a[d]
a[d] += 1
except KeyError:
a[d] = 1
try:
ans += b[e]
b[e] += 1
except KeyError:
b[e] = 1
if # TODO: Your code here:
c[d+e] = 0
else:
ans -= c[d+e]
c[d+e] += 2
print(ans)
|
for i in range(int(input())):
n= int(input())
a = dict()
b = dict()
c = dict()
ans = 0
for j in range(n):
d,e = str(input())
try:
ans += a[d]
a[d] += 1
except KeyError:
a[d] = 1
try:
ans += b[e]
b[e] += 1
except KeyError:
b[e] = 1
if {{completion}}:
c[d+e] = 0
else:
ans -= c[d+e]
c[d+e] += 2
print(ans)
|
d+e not in c
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
control_completion_000874
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) — the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) — the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) — the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
c = list(map(int,sys.stdin.readline().split()))
count = 0
L = [0] * (n+1)
for i in range(0,n):
L[a[i]] = b[i]
status = 1
for i in range(n):
if c[i] != 0:
L[a[i]] = 0
L[b[i]] = 0
for i in range(1,n+1):
key = i
xstatus = 1
status = 1
xcount= 0
while status == 1:
if L[key] == 0:
status = 0
if L[key] == i:
if # TODO: Your code here:
count += 1
status = 0
xcount += 1
x = L[key]
L[key] = 0
key = x
print((2 **count) % (10 ** 9 + 7))
|
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
c = list(map(int,sys.stdin.readline().split()))
count = 0
L = [0] * (n+1)
for i in range(0,n):
L[a[i]] = b[i]
status = 1
for i in range(n):
if c[i] != 0:
L[a[i]] = 0
L[b[i]] = 0
for i in range(1,n+1):
key = i
xstatus = 1
status = 1
xcount= 0
while status == 1:
if L[key] == 0:
status = 0
if L[key] == i:
if {{completion}}:
count += 1
status = 0
xcount += 1
x = L[key]
L[key] = 0
key = x
print((2 **count) % (10 ** 9 + 7))
|
xcount >= 1
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
control_completion_005921
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells: An empty cell, denoted with '.'. A stone, denoted with '*'. An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?
Input Specification: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o' — an empty cell, a stone, or an obstacle, respectively.
Output Specification: For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.
Code:
def res(s):
a=s.split('o');t=''
for i in a:t+=i.count('*')*'*'+i.count('.')*'.'+'o'
return t[:-1]
for _ in[0]*int(input()):
n,m=map(int,input().split())
a=[[*input()] for x in[0]*n]
b=[]
for i in range(m):b+=res(''.join([a[~j][i] for j in range(n)])),
for i in range(n):
for j in range(m):# TODO: Your code here
print()
print()
|
def res(s):
a=s.split('o');t=''
for i in a:t+=i.count('*')*'*'+i.count('.')*'.'+'o'
return t[:-1]
for _ in[0]*int(input()):
n,m=map(int,input().split())
a=[[*input()] for x in[0]*n]
b=[]
for i in range(m):b+=res(''.join([a[~j][i] for j in range(n)])),
for i in range(n):
for j in range(m):{{completion}}
print()
print()
|
print(b[j][~i],end='')
|
[{"input": "3\n6 10\n.*.*....*.\n.*.......*\n...o....o.\n.*.*....*.\n..........\n.o......o*\n2 9\n...***ooo\n.*o.*o.*o\n5 5\n*****\n*....\n*****\n....*\n*****", "output": ["..........\n...*....*.\n.*.o....o.\n.*........\n.*......**\n.o.*....o*\n\n....**ooo\n.*o**o.*o\n\n.....\n*...*\n*****\n*****\n*****"]}]
|
block_completion_000847
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.
Output Specification: If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.
Notes: NoteIn the first example the following sequence of swaps will suffice: $$$(2, 1), (1, 1)$$$, $$$(1, 2), (1, 3)$$$, $$$(2, 2), (2, 3)$$$, $$$(1, 4), (1, 5)$$$, $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.
Code:
import time
def main():
n = int(input())
curr = [[int(x) for x in input().split(" ")] for _ in range(2)]
want = [[int(x) for x in input().split(" ")] for _ in range(2)]
out = 0
s1 = 0
s2 = 0
for x in range(n):
out += abs(s1) + abs(s2)
s1 += curr[0][x]
s2 += curr[1][x]
s1 -= want[0][x]
s2 -= want[1][x]
if abs(s1 + s2) < abs(s1) + abs(s2):
if abs(s1) <= abs(s2):
out += abs(s1)
s2 += s1
s1 = 0
else:
# TODO: Your code here
if s1 != 0 or s2 != 0:
print(-1)
else:
print(out)
if __name__ == "__main__":
main()
|
import time
def main():
n = int(input())
curr = [[int(x) for x in input().split(" ")] for _ in range(2)]
want = [[int(x) for x in input().split(" ")] for _ in range(2)]
out = 0
s1 = 0
s2 = 0
for x in range(n):
out += abs(s1) + abs(s2)
s1 += curr[0][x]
s2 += curr[1][x]
s1 -= want[0][x]
s2 -= want[1][x]
if abs(s1 + s2) < abs(s1) + abs(s2):
if abs(s1) <= abs(s2):
out += abs(s1)
s2 += s1
s1 = 0
else:
{{completion}}
if s1 != 0 or s2 != 0:
print(-1)
else:
print(out)
if __name__ == "__main__":
main()
|
out += abs(s2)
s1 += s2
s2 = 0
|
[{"input": "5\n0 1 0 1 0\n1 1 0 0 1\n1 0 1 0 1\n0 0 1 1 0", "output": ["5"]}, {"input": "3\n1 0 0\n0 0 0\n0 0 0\n0 0 0", "output": ["-1"]}]
|
block_completion_004259
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.
Input Specification: The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$) — elements of given array.
Output Specification: In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.
Notes: NoteIn the first example $$$3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24$$$. Number $$$24$$$ is divisible by $$$4! = 24$$$.In the second example $$$3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18$$$, is divisible by $$$3! = 6$$$.In the third example $$$7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!$$$. It is easy to prove that this number is not divisible by $$$8!$$$.
Code:
a,b=map(int,input().split())
arr=[0]*500001
for i in map(int,input().split()):
arr[i]+=1
for i in range(1,500000):
arr[i+1]+=arr[i]//(i+1)
arr[i]%=i+1
if sum(arr[:b])==0:
print('Yes')
else:
# TODO: Your code here
|
a,b=map(int,input().split())
arr=[0]*500001
for i in map(int,input().split()):
arr[i]+=1
for i in range(1,500000):
arr[i+1]+=arr[i]//(i+1)
arr[i]%=i+1
if sum(arr[:b])==0:
print('Yes')
else:
{{completion}}
|
print('No')
|
[{"input": "6 4\n3 2 2 2 3 3", "output": ["Yes"]}, {"input": "8 3\n3 2 2 2 2 2 1 1", "output": ["Yes"]}, {"input": "7 8\n7 7 7 7 7 7 7", "output": ["No"]}, {"input": "10 5\n4 3 2 1 4 3 2 4 3 4", "output": ["No"]}, {"input": "2 500000\n499999 499999", "output": ["No"]}]
|
block_completion_006086
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells: An empty cell, denoted with '.'. A stone, denoted with '*'. An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?
Input Specification: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o' — an empty cell, a stone, or an obstacle, respectively.
Output Specification: For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.
Code:
I=lambda:map(int,input().split())
for _ in range(int(input())):
n,m=I()
a=[input() for _ in range(n)]
at=[''.join(col).split('o') for col in zip(*a)]
f=lambda s:''.join(sorted(s,reverse=True))
at=['o'.join(map(f, col)) for col in at]
for row in zip(*at):
# TODO: Your code here
|
I=lambda:map(int,input().split())
for _ in range(int(input())):
n,m=I()
a=[input() for _ in range(n)]
at=[''.join(col).split('o') for col in zip(*a)]
f=lambda s:''.join(sorted(s,reverse=True))
at=['o'.join(map(f, col)) for col in at]
for row in zip(*at):
{{completion}}
|
print(''.join(row))
|
[{"input": "3\n6 10\n.*.*....*.\n.*.......*\n...o....o.\n.*.*....*.\n..........\n.o......o*\n2 9\n...***ooo\n.*o.*o.*o\n5 5\n*****\n*....\n*****\n....*\n*****", "output": ["..........\n...*....*.\n.*.o....o.\n.*........\n.*......**\n.o.*....o*\n\n....**ooo\n.*o**o.*o\n\n.....\n*...*\n*****\n*****\n*****"]}]
|
block_completion_000853
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.
Input Specification: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string consisting of six digits.
Output Specification: Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if the given ticket is lucky, 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, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is "YES".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is "NO".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is "YES".
Code:
t = int(input(""))
for i in range(t):
ticket = input("")
if int(ticket[0])+int(ticket[1])+int(ticket[2]) == int(ticket[3])+int(ticket[4])+int(ticket[5]):
print("YES")
else:
# TODO: Your code here
|
t = int(input(""))
for i in range(t):
ticket = input("")
if int(ticket[0])+int(ticket[1])+int(ticket[2]) == int(ticket[3])+int(ticket[4])+int(ticket[5]):
print("YES")
else:
{{completion}}
|
print("NO")
|
[{"input": "5\n213132\n973894\n045207\n000000\n055776", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_007625
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following: For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.
Output Specification: For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.
Notes: NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.
Code:
case=int(input())
for i in range(case):
n,m = (int(v) for v in input().split())
tmp=0
for j in range(n):
list1 = [int(v) for v in input().split()]
value = 0
for k in range(m):
value += list1[k]*(k+1)
if j==0:
tmp = value
else:
if value > tmp:
print(str(j+1)+" "+str(value-tmp))
elif # TODO: Your code here:
print("1 "+str(tmp-value))
tmp = value
else:
pass
|
case=int(input())
for i in range(case):
n,m = (int(v) for v in input().split())
tmp=0
for j in range(n):
list1 = [int(v) for v in input().split()]
value = 0
for k in range(m):
value += list1[k]*(k+1)
if j==0:
tmp = value
else:
if value > tmp:
print(str(j+1)+" "+str(value-tmp))
elif {{completion}}:
print("1 "+str(tmp-value))
tmp = value
else:
pass
|
value < tmp
|
[{"input": "7\n3 9\n0 1 2 0 0 2 1 1 0\n0 1 1 1 2 0 0 2 0\n0 1 2 0 0 1 2 1 0\n3 7\n25 15 20 15 25 20 20\n26 14 20 14 26 20 20\n25 15 20 15 20 20 25\n3 9\n25 15 20 15 25 20 20 20 20\n26 14 20 14 26 20 20 20 20\n25 15 20 15 25 15 20 20 25\n3 11\n25 15 20 15 25 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20\n25 15 20 15 25 20 15 20 20 20 25\n3 13\n25 15 20 15 25 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 15 20 20 20 20 25\n3 15\n25 15 20 15 25 20 20 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 20 15 20 20 20 20 20 25\n3 9\n909459 479492 676924 224197 162866 164495 193268 742456 728277\n948845 455424 731850 327890 304150 237351 251763 225845 798316\n975446 401170 792914 272263 300770 242037 236619 334316 725899", "output": ["3 1\n3 10\n3 15\n3 20\n3 25\n3 30\n1 1378716"]}]
|
control_completion_002577
|
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 j == "G":
# TODO: Your code here
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 j == "G":
{{completion}}
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 = "B"
|
[{"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"]}]
|
block_completion_008471
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$ — the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$) — the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.
Output Specification: For each query, print a single integer — the maximum total value of items received for free for one purchase.
Notes: NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.
Code:
Y=lambda:map(int,input().split())
O=[];n,q=Y();p=sorted(Y())[::-1];s=[0]
for i in p:s+=[s[-1]+i]
for # TODO: Your code here:x,y=Y();O+=[str(s[x]-s[x-y])]
print('\n'.join(O))
|
Y=lambda:map(int,input().split())
O=[];n,q=Y();p=sorted(Y())[::-1];s=[0]
for i in p:s+=[s[-1]+i]
for {{completion}}:x,y=Y();O+=[str(s[x]-s[x-y])]
print('\n'.join(O))
|
_ in[0]*q
|
[{"input": "5 3\n5 3 1 5 2\n3 2\n1 1\n5 3", "output": ["8\n5\n6"]}]
|
control_completion_000507
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i > 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i < i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty): Choose a card $$$x$$$ such that no other cards are hanging onto it. Append the number written on card $$$x$$$ to the end of $$$s$$$. If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$. Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) describing which card that each card hangs onto.
Output Specification: Print a single integer — the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.
Notes: NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order: Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 > w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$. Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$. Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$. Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 > w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$. Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$. Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.
Code:
import sys
n = int(input())
a = [int(x)-1 for x in sys.stdin.readline().split()]
depth = [1]*n
best = [0]*n
for i in range(n-1, -1, -1):
best[i] = max(best[i], depth[i])
if # TODO: Your code here:
parent = a[i-1]
depth[parent] = max(depth[parent], 1 + depth[i])
best[parent] += best[i]
print(best[0])
|
import sys
n = int(input())
a = [int(x)-1 for x in sys.stdin.readline().split()]
depth = [1]*n
best = [0]*n
for i in range(n-1, -1, -1):
best[i] = max(best[i], depth[i])
if {{completion}}:
parent = a[i-1]
depth[parent] = max(depth[parent], 1 + depth[i])
best[parent] += best[i]
print(best[0])
|
i != 0
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
control_completion_004632
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: The derby between Milan and Inter is happening soon, and you have been chosen as the assistant referee for the match, also known as linesman. Your task is to move along the touch-line, namely the side of the field, always looking very carefully at the match to check for offside positions and other offences.Football is an extremely serious matter in Italy, and thus it is fundamental that you keep very close track of the ball for as much time as possible. This means that you want to maximise the number of kicks which you monitor closely. You are able to monitor closely a kick if, when it happens, you are in the position along the touch-line with minimum distance from the place where the kick happens.Fortunately, expert analysts have been able to accurately predict all the kicks which will occur during the game. That is, you have been given two lists of integers, $$$t_1, \ldots, t_n$$$ and $$$a_1, \ldots, a_n$$$, indicating that $$$t_i$$$ seconds after the beginning of the match the ball will be kicked and you can monitor closely such kick if you are at the position $$$a_i$$$ along the touch-line. At the beginning of the game you start at position $$$0$$$ and the maximum speed at which you can walk along the touch-line is $$$v$$$ units per second (i.e., you can change your position by at most $$$v$$$ each second). What is the maximum number of kicks that you can monitor closely?
Input Specification: The first line contains two integers $$$n$$$ and $$$v$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le v \le 10^6$$$) — the number of kicks that will take place and your maximum speed. The second line contains $$$n$$$ integers $$$t_1, \ldots, t_n$$$ ($$$1 \le t_i \le 10^9$$$) — the times of the kicks in the match. The sequence of times is guaranteed to be strictly increasing, i.e., $$$t_1 < t_2 < \cdots < t_n$$$. The third line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the positions along the touch-line where you have to be to monitor closely each kick.
Output Specification: Print the maximum number of kicks that you can monitor closely.
Notes: NoteIn the first sample, it is possible to move to the right at maximum speed for the first $$$3.5$$$ seconds and stay at position $$$7$$$ until the first kick happens, and then immediately move right also at maximum speed to watch the second kick at position $$$17$$$. There is no way to monitor closely the third kick after the second kick, so at most $$$2$$$ kicks can be seen.
Code:
from bisect import bisect_right,bisect_left
n,v = map(int,input().split())
t = [*map(int,input().split())]
a = [*map(int,input().split())]
res = []
for i in range(n):
xi,yi = t[i]*v+a[i],t[i]*v-a[i]
if(xi>=0 and yi>=0):
res.append((xi,yi))
res.sort()
dp = [float("inf")]*(n+3)
dp[0] = 0
dp[n+2] = 0
for i in range(len(res)):
pos = bisect_right(dp,res[i][1],0,n+2)
dp[pos] = res[i][1]
for i in range(n,-1,-1):
if# TODO: Your code here:
print(i)
break
|
from bisect import bisect_right,bisect_left
n,v = map(int,input().split())
t = [*map(int,input().split())]
a = [*map(int,input().split())]
res = []
for i in range(n):
xi,yi = t[i]*v+a[i],t[i]*v-a[i]
if(xi>=0 and yi>=0):
res.append((xi,yi))
res.sort()
dp = [float("inf")]*(n+3)
dp[0] = 0
dp[n+2] = 0
for i in range(len(res)):
pos = bisect_right(dp,res[i][1],0,n+2)
dp[pos] = res[i][1]
for i in range(n,-1,-1):
if{{completion}}:
print(i)
break
|
(dp[i]!=float("inf"))
|
[{"input": "3 2\n5 10 15\n7 17 29", "output": ["2"]}, {"input": "5 1\n5 7 8 11 13\n3 3 -2 -2 4", "output": ["3"]}, {"input": "1 2\n3\n7", "output": ["0"]}]
|
control_completion_001084
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Suppose you have an integer $$$v$$$. In one operation, you can: either set $$$v = (v + 1) \bmod 32768$$$ or set $$$v = (2 \cdot v) \bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$?
Input Specification: The first line contains the single integer $$$n$$$ ($$$1 \le n \le 32768$$$) — the number of integers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 32768$$$).
Output Specification: Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the minimum number of operations required to make $$$a_i$$$ equal to $$$0$$$.
Notes: NoteLet's consider each $$$a_i$$$: $$$a_1 = 19$$$. You can, firstly, increase it by one to get $$$20$$$ and then multiply it by two $$$13$$$ times. You'll get $$$0$$$ in $$$1 + 13 = 14$$$ steps. $$$a_2 = 32764$$$. You can increase it by one $$$4$$$ times: $$$32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0$$$. $$$a_3 = 10240$$$. You can multiply it by two $$$4$$$ times: $$$10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0$$$. $$$a_4 = 49$$$. You can multiply it by two $$$15$$$ times.
Code:
n,s=open(0)
for # TODO: Your code here:print(min(-x%2**i-i+15for i in range(16)))
|
n,s=open(0)
for {{completion}}:print(min(-x%2**i-i+15for i in range(16)))
|
x in map(int,s.split())
|
[{"input": "4\n19 32764 10240 49", "output": ["14 4 4 15"]}]
|
control_completion_003302
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider an array $$$a$$$ of $$$n$$$ positive integers.You may perform the following operation: select two indices $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$), then decrease all elements $$$a_l, a_{l + 1}, \dots, a_r$$$ by $$$1$$$. Let's call $$$f(a)$$$ the minimum number of operations needed to change array $$$a$$$ into an array of $$$n$$$ zeros.Determine if for all permutations$$$^\dagger$$$ $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true. $$$^\dagger$$$ An array $$$b$$$ is a permutation of an array $$$a$$$ if $$$b$$$ consists of the elements of $$$a$$$ in arbitrary order. For example, $$$[4,2,3,4]$$$ is a permutation of $$$[3,2,4,4]$$$ while $$$[1,2,2]$$$ is not a permutation of $$$[1,2,3]$$$.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — description of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print "YES" (without quotes) if for all permutations $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case, we can change all elements to $$$0$$$ in $$$5$$$ operations. It can be shown that no permutation of $$$[2, 3, 5, 4]$$$ requires less than $$$5$$$ operations to change all elements to $$$0$$$.In the third test case, we need $$$5$$$ operations to change all elements to $$$0$$$, while $$$[2, 3, 3, 1]$$$ only needs $$$3$$$ operations.
Code:
import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]
def next(): return tokens.pop()
def nextInt(): return int(next())
def nextFloat(): return float(next())
def getIntArray(n): return [nextInt() for _ in range(n)]
def getFloatArray(n): return [nextFloat() for _ in range(n)]
def getStringArray(n): return [next() for _ in range(n)]
def isMountain(ar):
prefixInc = [False] * len(ar)
prefixInc[0] = 1
for i in range(1, len(ar)):
prefixInc[i] = prefixInc[i - 1] and ar[i - 1] <= ar[i]
suffixInc = [0] * len(ar)
suffixInc[-1] = 1
for i in range(len(ar) - 2, -1, -1):
suffixInc[i] = suffixInc[i + 1] and ar[i] >= ar[i + 1]
ans = prefixInc[-1] or suffixInc[0]
for i in range(len(ar)):
ans = ans or (prefixInc[i] and suffixInc[i])
return ans
testcase = True
def solve(testcase = 1):
N = nextInt()
A = getIntArray(N)
print("yes" if isMountain(A) else "no")
if testcase is None:
testcaseCount = 1
while tokens:
solve(testcaseCount)
testcaseCount += 1
else:
testcaseCount = nextInt() if testcase else 1
for # TODO: Your code here:
solve(tc + 1)
assert not tokens
|
import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]
def next(): return tokens.pop()
def nextInt(): return int(next())
def nextFloat(): return float(next())
def getIntArray(n): return [nextInt() for _ in range(n)]
def getFloatArray(n): return [nextFloat() for _ in range(n)]
def getStringArray(n): return [next() for _ in range(n)]
def isMountain(ar):
prefixInc = [False] * len(ar)
prefixInc[0] = 1
for i in range(1, len(ar)):
prefixInc[i] = prefixInc[i - 1] and ar[i - 1] <= ar[i]
suffixInc = [0] * len(ar)
suffixInc[-1] = 1
for i in range(len(ar) - 2, -1, -1):
suffixInc[i] = suffixInc[i + 1] and ar[i] >= ar[i + 1]
ans = prefixInc[-1] or suffixInc[0]
for i in range(len(ar)):
ans = ans or (prefixInc[i] and suffixInc[i])
return ans
testcase = True
def solve(testcase = 1):
N = nextInt()
A = getIntArray(N)
print("yes" if isMountain(A) else "no")
if testcase is None:
testcaseCount = 1
while tokens:
solve(testcaseCount)
testcaseCount += 1
else:
testcaseCount = nextInt() if testcase else 1
for {{completion}}:
solve(tc + 1)
assert not tokens
|
tc in range(testcaseCount)
|
[{"input": "3\n\n4\n\n2 3 5 4\n\n3\n\n1 2 3\n\n4\n\n3 1 3 2", "output": ["YES\nYES\nNO"]}]
|
control_completion_001993
|
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: A row of $$$n$$$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}$$$ and as $$$\color{red}{\texttt{R}}\color{blue}{\texttt{B}}$$$.During use, the stamp must completely fit on the given $$$n$$$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\color{blue}{\texttt{B}}\texttt{W}$$$ could be $$$\texttt{WWWWW} \to \texttt{WW}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\texttt{W} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\texttt{W} \to \color{blue}{\texttt{B}}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}\texttt{W}$$$. Here $$$\texttt{W}$$$, $$$\color{red}{\texttt{R}}$$$, and $$$\color{blue}{\texttt{B}}$$$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the picture. The second line of each test case contains a string $$$s$$$ — the picture you need to make. It is guaranteed that the length of $$$s$$$ is $$$n$$$ and that $$$s$$$ only consists of the characters $$$\texttt{W}$$$, $$$\texttt{R}$$$, and $$$\texttt{B}$$$, representing a white, red, or blue cell, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output "YES" if it possible to make the picture using the stamp zero or more times, 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: NoteThe first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is "NO".For the fifth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{blue}{\texttt{B}}$$$.For the sixth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}$$$.For the seventh test case, you don't need to use the stamp at all.
Code:
for _ in range(int(input())) :
# TODO: Your code here
|
for _ in range(int(input())) :
{{completion}}
|
l = int(input())
print("NO" if any (len(set(x)) == 1 for x in input().split('W') ) else "YES")
|
[{"input": "12\n5\nBRBBW\n1\nB\n2\nWB\n2\nRW\n3\nBRB\n3\nRBB\n7\nWWWWWWW\n9\nRBWBWRRBW\n10\nBRBRBRBRRB\n12\nBBBRWWRRRWBR\n10\nBRBRBRBRBW\n5\nRBWBW", "output": ["YES\nNO\nNO\nNO\nYES\nYES\nYES\nNO\nYES\nNO\nYES\nNO"]}]
|
block_completion_000924
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following: For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.
Output Specification: For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.
Notes: NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.
Code:
case=int(input())
for i in range(case):
n,m = (int(v) for v in input().split())
tmp=0
for j in range(n):
list1 = [int(v) for v in input().split()]
value = 0
for k in range(m):
value += list1[k]*(k+1)
if j==0:
tmp = value
else:
if value > tmp:
print(str(j+1)+" "+str(value-tmp))
elif value < tmp:
print("1 "+str(tmp-value))
tmp = value
else:
# TODO: Your code here
|
case=int(input())
for i in range(case):
n,m = (int(v) for v in input().split())
tmp=0
for j in range(n):
list1 = [int(v) for v in input().split()]
value = 0
for k in range(m):
value += list1[k]*(k+1)
if j==0:
tmp = value
else:
if value > tmp:
print(str(j+1)+" "+str(value-tmp))
elif value < tmp:
print("1 "+str(tmp-value))
tmp = value
else:
{{completion}}
|
pass
|
[{"input": "7\n3 9\n0 1 2 0 0 2 1 1 0\n0 1 1 1 2 0 0 2 0\n0 1 2 0 0 1 2 1 0\n3 7\n25 15 20 15 25 20 20\n26 14 20 14 26 20 20\n25 15 20 15 20 20 25\n3 9\n25 15 20 15 25 20 20 20 20\n26 14 20 14 26 20 20 20 20\n25 15 20 15 25 15 20 20 25\n3 11\n25 15 20 15 25 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20\n25 15 20 15 25 20 15 20 20 20 25\n3 13\n25 15 20 15 25 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 15 20 20 20 20 25\n3 15\n25 15 20 15 25 20 20 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 20 15 20 20 20 20 20 25\n3 9\n909459 479492 676924 224197 162866 164495 193268 742456 728277\n948845 455424 731850 327890 304150 237351 251763 225845 798316\n975446 401170 792914 272263 300770 242037 236619 334316 725899", "output": ["3 1\n3 10\n3 15\n3 20\n3 25\n3 30\n1 1378716"]}]
|
block_completion_002630
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$You can apply the following operation an arbitrary number of times: select an index $$$i$$$ ($$$1 \le i \le n$$$) and replace the value of the element $$$a_i$$$ with the value $$$a_i + (a_i \bmod 10)$$$, where $$$a_i \bmod 10$$$ is the remainder of the integer dividing $$$a_i$$$ by $$$10$$$. For a single index (value $$$i$$$), this operation can be applied multiple times. If the operation is applied repeatedly to the same index, then the current value of $$$a_i$$$ is taken into account each time. For example, if $$$a_i=47$$$ then after the first operation we get $$$a_i=47+7=54$$$, and after the second operation we get $$$a_i=54+4=58$$$.Check if it is possible to make all array elements equal by applying multiple (possibly zero) operations.For example, you have an array $$$[6, 11]$$$. Let's apply this operation to the first element of the array. Let's replace $$$a_1 = 6$$$ with $$$a_1 + (a_1 \bmod 10) = 6 + (6 \bmod 10) = 6 + 6 = 12$$$. We get the array $$$[12, 11]$$$. Then apply this operation to the second element of the array. Let's replace $$$a_2 = 11$$$ with $$$a_2 + (a_2 \bmod 10) = 11 + (11 \bmod 10) = 11 + 1 = 12$$$. We get the array $$$[12, 12]$$$. Thus, by applying $$$2$$$ operations, you can make all elements of an array equal.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. What follows is a description of each test case. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \le a_i \le 10^9$$$) — array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case print: YES if it is possible to make all array elements equal; NO otherwise. You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer) .
Notes: NoteThe first test case is clarified above.In the second test case, it is impossible to make all array elements equal.In the third test case, you need to apply this operation once to all elements equal to $$$5$$$.In the fourth test case, you need to apply this operation to all elements until they become equal to $$$8$$$.In the fifth test case, it is impossible to make all array elements equal.In the sixth test case, you need to apply this operation to all elements until they become equal to $$$102$$$.
Code:
# Problem - https://codeforces.com/contest/1714/problem/E
# Editorial - https://codeforces.com/blog/entry/105549
# Tags - brute force, math, number theory, *1400
import sys
import typing
# Read stdin and remove newline elements
stdin = [line.strip() for line in sys.stdin.readlines() if line != '\n']
stdin_counter = 0
cycle_for_2 = 20 # 2 => 2 + 2 => 4 + 4 => 8 + 8 => 16 + 6 => 22 - 2 = 20
def take_from_stdin():
global stdin_counter
result = stdin[stdin_counter]
stdin_counter += 1
return result
def solve(arr: typing.List[int]):
has_2 = False
has_0 = False
for i in range(len(arr)):
mod_10 = arr[i] % 10
if mod_10 == 2:
has_2 = True
if mod_10 == 0:
has_0 = True
while mod_10 != 2 and mod_10 != 0:
arr[i] += mod_10
mod_10 = arr[i] % 10
if mod_10 == 2:
has_2 = True
if mod_10 == 0:
# TODO: Your code here
if has_0 and has_2:
return "NO"
if has_2:
for i in range(len(arr)):
arr[i] = arr[i] % 20
if len(set(arr)) == 1:
return "YES"
return "NO"
def main():
test_count = int(take_from_stdin())
for _ in range(test_count):
_ = int(take_from_stdin())
arr = [int(x) for x in take_from_stdin().split()]
print(solve(arr))
main()
|
# Problem - https://codeforces.com/contest/1714/problem/E
# Editorial - https://codeforces.com/blog/entry/105549
# Tags - brute force, math, number theory, *1400
import sys
import typing
# Read stdin and remove newline elements
stdin = [line.strip() for line in sys.stdin.readlines() if line != '\n']
stdin_counter = 0
cycle_for_2 = 20 # 2 => 2 + 2 => 4 + 4 => 8 + 8 => 16 + 6 => 22 - 2 = 20
def take_from_stdin():
global stdin_counter
result = stdin[stdin_counter]
stdin_counter += 1
return result
def solve(arr: typing.List[int]):
has_2 = False
has_0 = False
for i in range(len(arr)):
mod_10 = arr[i] % 10
if mod_10 == 2:
has_2 = True
if mod_10 == 0:
has_0 = True
while mod_10 != 2 and mod_10 != 0:
arr[i] += mod_10
mod_10 = arr[i] % 10
if mod_10 == 2:
has_2 = True
if mod_10 == 0:
{{completion}}
if has_0 and has_2:
return "NO"
if has_2:
for i in range(len(arr)):
arr[i] = arr[i] % 20
if len(set(arr)) == 1:
return "YES"
return "NO"
def main():
test_count = int(take_from_stdin())
for _ in range(test_count):
_ = int(take_from_stdin())
arr = [int(x) for x in take_from_stdin().split()]
print(solve(arr))
main()
|
has_0 = True
|
[{"input": "10\n\n2\n\n6 11\n\n3\n\n2 18 22\n\n5\n\n5 10 5 10 5\n\n4\n\n1 2 4 8\n\n2\n\n4 5\n\n3\n\n93 96 102\n\n2\n\n40 6\n\n2\n\n50 30\n\n2\n\n22 44\n\n2\n\n1 5", "output": ["Yes\nNo\nYes\nYes\nNo\nYes\nNo\nNo\nYes\nNo"]}]
|
block_completion_006708
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
for _ in range(int(input())):
met = []
res = []
judge = True
i = 0
while i < 8:
tmp = input()
met.append(tmp)
if tmp != '':
i += 1
if # TODO: Your code here:
print("R")
judge = False
if judge:
print("B")
# for i in met:
# print(i)
|
for _ in range(int(input())):
met = []
res = []
judge = True
i = 0
while i < 8:
tmp = input()
met.append(tmp)
if tmp != '':
i += 1
if {{completion}}:
print("R")
judge = False
if judge:
print("B")
# for i in met:
# print(i)
|
tmp == "R" * 8 and judge
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
control_completion_005709
|
control_fixed
|
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())
answer = [0] * (n + 1)
dp = [1] + [0] * n
MIN = 0
while MIN + k <= n:
mod = [0 for _ in range(k)]
for # TODO: Your code here:
dp[i], mod[i % k] = mod[i % k], dp[i] + mod[i % k]
mod[i % k] %= 998244353
answer[i] += dp[i]
answer[i] %= 998244353
MIN += k
k += 1
print(*answer[1:])
|
n, k = map(int, input().split())
answer = [0] * (n + 1)
dp = [1] + [0] * n
MIN = 0
while MIN + k <= n:
mod = [0 for _ in range(k)]
for {{completion}}:
dp[i], mod[i % k] = mod[i % k], dp[i] + mod[i % k]
mod[i % k] %= 998244353
answer[i] += dp[i]
answer[i] %= 998244353
MIN += k
k += 1
print(*answer[1:])
|
i in range(MIN, 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_008069
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Input Specification: The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.
Notes: NoteIn the first test case, the array $$$a = [2]$$$ after the first query.In the third test case, the array $$$a$$$ is modified as follows: $$$[1, 3, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 2, 4, 10, 48]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[7, 9, 7, 9, 15, 53]$$$ $$$\rightarrow$$$ $$$[10, 12, 10, 12, 18, 56]$$$ $$$\rightarrow$$$ $$$[22, 24, 22, 24, 30, 68]$$$ $$$\rightarrow$$$ $$$[23, 25, 23, 25, 31, 69]$$$.
Code:
from sys import stdin
from collections import deque
lst = list(map(int, stdin.read().split()))
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
return inp()[0]
t = inp1()
for _ in range(t):
n = inp1()
q = inp1()
a = inp(n)
tx = [inp(2) for _ in range(q)]
odd = 0
even = 0
for i in a:
if i % 2 == 0:
even +=1
else:
odd +=1
ret = sum(a)
for i in tx:
if i[0] == 0:
ret += even * i[1]
if i[1] % 2 != 0:
odd = n
even = 0
else:
ret += odd * i[1]
if # TODO: Your code here:
even = n
odd = 0
print(ret)
|
from sys import stdin
from collections import deque
lst = list(map(int, stdin.read().split()))
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
return inp()[0]
t = inp1()
for _ in range(t):
n = inp1()
q = inp1()
a = inp(n)
tx = [inp(2) for _ in range(q)]
odd = 0
even = 0
for i in a:
if i % 2 == 0:
even +=1
else:
odd +=1
ret = sum(a)
for i in tx:
if i[0] == 0:
ret += even * i[1]
if i[1] % 2 != 0:
odd = n
even = 0
else:
ret += odd * i[1]
if {{completion}}:
even = n
odd = 0
print(ret)
|
i[1] % 2 != 0
|
[{"input": "4\n\n1 1\n\n1\n\n1 1\n\n3 3\n\n1 2 4\n\n0 2\n\n1 3\n\n0 5\n\n6 7\n\n1 3 2 4 10 48\n\n1 6\n\n0 5\n\n0 4\n\n0 5\n\n1 3\n\n0 12\n\n0 1\n\n6 7\n\n1000000000 1000000000 1000000000 11 15 17\n\n0 17\n\n1 10000\n\n1 51\n\n0 92\n\n0 53\n\n1 16\n\n0 1", "output": ["2\n11\n14\n29\n80\n100\n100\n100\n118\n190\n196\n3000000094\n3000060094\n3000060400\n3000060952\n3000061270\n3000061366\n3000061366"]}]
|
control_completion_004093
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Nastya baked $$$m$$$ pancakes and spread them on $$$n$$$ dishes. The dishes are in a row and numbered from left to right. She put $$$a_i$$$ pancakes on the dish with the index $$$i$$$.Seeing the dishes, Vlad decided to bring order to the stacks and move some pancakes. In one move, he can shift one pancake from any dish to the closest one, that is, select the dish $$$i$$$ ($$$a_i > 0$$$) and do one of the following: if $$$i > 1$$$, put the pancake on a dish with the previous index, after this move $$$a_i = a_i - 1$$$ and $$$a_{i - 1} = a_{i - 1} + 1$$$; if $$$i < n$$$, put the pancake on a dish with the following index, after this move $$$a_i = a_i - 1$$$ and $$$a_{i + 1} = a_{i + 1} + 1$$$.Vlad wants to make the array $$$a$$$non-increasing, after moving as few pancakes as possible. Help him find the minimum number of moves needed for this.The array $$$a=[a_1, a_2,\dots,a_n]$$$ is called non-increasing if $$$a_i \ge a_{i+1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$.
Input Specification: The first line of the input contains two numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 250$$$) — the number of dishes and the number of pancakes, respectively. The second line contains $$$n$$$ numbers $$$a_i$$$ ($$$0 \le a_i \le m$$$), the sum of all $$$a_i$$$ is equal to $$$m$$$.
Output Specification: Print a single number: the minimum number of moves required to make the array $$$a$$$ non-increasing.
Notes: NoteIn the first example, you first need to move the pancake from the dish $$$1$$$, after which $$$a = [4, 4, 2, 3, 3, 3]$$$. After that, you need to move the pancake from the dish $$$2$$$ to the dish $$$3$$$ and the array will become non-growing $$$a = [4, 3, 3, 3, 3, 3]$$$.
Code:
from functools import cache
from math import inf
from itertools import accumulate
def solve(A, m):
n = len(A)
A.reverse()
@cache
def dp(i, val, balance):
if abs(balance) > m:
return inf
if # TODO: Your code here:
return inf
if i == n:
return 0 if balance == 0 else inf
curr = A[i] + balance
take = abs(curr - val) + dp(i + 1, val, curr - val)
skip = dp(i, val + 1, balance)
return min(take, skip)
return dp(0, 0, 0)
n, m = map(int, input().split())
A = list(map(int, input().split()))
print(solve(A, m))
|
from functools import cache
from math import inf
from itertools import accumulate
def solve(A, m):
n = len(A)
A.reverse()
@cache
def dp(i, val, balance):
if abs(balance) > m:
return inf
if {{completion}}:
return inf
if i == n:
return 0 if balance == 0 else inf
curr = A[i] + balance
take = abs(curr - val) + dp(i + 1, val, curr - val)
skip = dp(i, val + 1, balance)
return min(take, skip)
return dp(0, 0, 0)
n, m = map(int, input().split())
A = list(map(int, input().split()))
print(solve(A, m))
|
(n - i) * val > m
|
[{"input": "6 19\n5 3 2 3 3 3", "output": ["2"]}, {"input": "3 6\n3 2 1", "output": ["0"]}, {"input": "3 6\n2 1 3", "output": ["1"]}, {"input": "6 19\n3 4 3 3 5 1", "output": ["3"]}, {"input": "10 1\n0 0 0 0 0 0 0 0 0 1", "output": ["9"]}]
|
control_completion_003521
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i > 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i < i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty): Choose a card $$$x$$$ such that no other cards are hanging onto it. Append the number written on card $$$x$$$ to the end of $$$s$$$. If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$. Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) describing which card that each card hangs onto.
Output Specification: Print a single integer — the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.
Notes: NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order: Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 > w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$. Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$. Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$. Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 > w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$. Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$. Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.
Code:
import sys
n = int(input())
a = [int(x)-1 for x in sys.stdin.readline().split()]
depth = [1]*n
best = [0]*n
for i in range(n-1, -1, -1):
best[i] = max(best[i], depth[i])
if i != 0:
# TODO: Your code here
print(best[0])
|
import sys
n = int(input())
a = [int(x)-1 for x in sys.stdin.readline().split()]
depth = [1]*n
best = [0]*n
for i in range(n-1, -1, -1):
best[i] = max(best[i], depth[i])
if i != 0:
{{completion}}
print(best[0])
|
parent = a[i-1]
depth[parent] = max(depth[parent], 1 + depth[i])
best[parent] += best[i]
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004724
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones and an integer $$$k$$$. In one operation you can do one of the following: Select $$$2$$$ consecutive elements of $$$a$$$ and replace them with their minimum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-1$$$). This operation decreases the size of $$$a$$$ by $$$1$$$. Select $$$k$$$ consecutive elements of $$$a$$$ and replace them with their maximum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \max(a_{i}, a_{i+1}, \ldots, a_{i+k-1}), a_{i+k}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-k+1$$$). This operation decreases the size of $$$a$$$ by $$$k-1$$$. Determine if it's possible to turn $$$a$$$ into $$$[1]$$$ after several (possibly zero) operations.
Input Specification: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 50$$$), the size of array $$$a$$$ and the length of segments that you can perform second type operation on. The second line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$.
Output Specification: For each test case, if it is possible to turn $$$a$$$ into $$$[1]$$$, print "YES", otherwise print "NO".
Notes: NoteIn the first test case, you can perform the second type operation on second and third elements so $$$a$$$ becomes $$$[0, 1]$$$, then you can perform the second type operation on first and second elements, so $$$a$$$ turns to $$$[1]$$$.In the fourth test case, it's obvious to see that you can't make any $$$1$$$, no matter what you do.In the fifth test case, you can first perform a type 2 operation on the first three elements so that $$$a$$$ becomes $$$[1, 0, 0, 1]$$$, then perform a type 2 operation on the elements in positions two through four, so that $$$a$$$ becomes $$$[1, 1]$$$, and finally perform the first type operation on the remaining elements, so that $$$a$$$ becomes $$$[1]$$$.
Code:
from sys import stdin
from collections import deque
lst = list(map(int, stdin.read().split()))
_s = 0
def inp(n=1):
# TODO: Your code here
def inp1():
return inp()[0]
t = inp1()
for _ in range(t):
n = inp1()
k = inp1()
a = set(inp(n))
print("YES" if 1 in a else "NO")
|
from sys import stdin
from collections import deque
lst = list(map(int, stdin.read().split()))
_s = 0
def inp(n=1):
{{completion}}
def inp1():
return inp()[0]
t = inp1()
for _ in range(t):
n = inp1()
k = inp1()
a = set(inp(n))
print("YES" if 1 in a else "NO")
|
global _s
ret = lst[_s:_s + n]
_s += n
return ret
|
[{"input": "7\n\n3 2\n\n0 1 0\n\n5 3\n\n1 0 1 1 0\n\n2 2\n\n1 1\n\n4 4\n\n0 0 0 0\n\n6 3\n\n0 0 1 0 0 1\n\n7 5\n\n1 1 1 1 1 1 1\n\n5 3\n\n0 0 1 0 0", "output": ["YES\nYES\nYES\nNO\nYES\nYES\nYES"]}]
|
block_completion_006994
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a grid with $$$n$$$ rows and $$$m$$$ columns. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$. All numbers are equal to $$$1$$$ or to $$$-1$$$. You start from the square $$$(1, 1)$$$ and can move one square down or one square to the right at a time. In the end, you want to end up at the square $$$(n, m)$$$.Is it possible to move in such a way so that the sum of the values written in all the visited cells (including $$$a_{11}$$$ and $$$a_{nm}$$$) is $$$0$$$?
Input Specification: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$a_{ij} = 1$$$ or $$$-1$$$) — the element in the cell $$$(i, j)$$$. It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$10^6$$$.
Output Specification: For each test case, print "YES" if there exists a path from the top left to the bottom right that adds up to $$$0$$$, and "NO" otherwise. You can output each letter in any case.
Notes: NoteOne possible path for the fourth test case is given in the picture in the statement.
Code:
import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]
def next(): return tokens.pop()
def nextInt(): return int(next())
def nextFloat(): return float(next())
def getIntArray(n): return [nextInt() for _ in range(n)]
def getFloatArray(n): return [nextFloat() for _ in range(n)]
def getStringArray(n): return [next() for _ in range(n)]
testcase = True
def solve(testcase = 1):
N, M = nextInt(), nextInt()
A = [getIntArray(M) for _ in range(N)]
if N < M:
A = [list(i) for i in zip(*A)]
N, M = M, N
def get(sum):
return sum + N + M
B = [[0] * M for i in range(N)]
B[0][0] |= 1 << get(A[0][0])
for i in range(N):
for j in range(M):
if i == 0 and j == 0: # TODO: Your code here
if i: B[i][j] |= B[i - 1][j]
if j: B[i][j] |= B[i][j - 1]
if A[i][j] > 0: B[i][j] <<= 1
else: B[i][j] >>= 1
if i: B[i - 1] = None
print("YES" if B[-1][-1] & (1 << get(0)) else "NO")
pass
if testcase is None:
testcaseCount = 1
while tokens:
solve(testcaseCount)
testcaseCount += 1
else:
testcaseCount = nextInt() if testcase else 1
for tc in range(testcaseCount):
solve(tc + 1)
assert not tokens
|
import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]
def next(): return tokens.pop()
def nextInt(): return int(next())
def nextFloat(): return float(next())
def getIntArray(n): return [nextInt() for _ in range(n)]
def getFloatArray(n): return [nextFloat() for _ in range(n)]
def getStringArray(n): return [next() for _ in range(n)]
testcase = True
def solve(testcase = 1):
N, M = nextInt(), nextInt()
A = [getIntArray(M) for _ in range(N)]
if N < M:
A = [list(i) for i in zip(*A)]
N, M = M, N
def get(sum):
return sum + N + M
B = [[0] * M for i in range(N)]
B[0][0] |= 1 << get(A[0][0])
for i in range(N):
for j in range(M):
if i == 0 and j == 0: {{completion}}
if i: B[i][j] |= B[i - 1][j]
if j: B[i][j] |= B[i][j - 1]
if A[i][j] > 0: B[i][j] <<= 1
else: B[i][j] >>= 1
if i: B[i - 1] = None
print("YES" if B[-1][-1] & (1 << get(0)) else "NO")
pass
if testcase is None:
testcaseCount = 1
while tokens:
solve(testcaseCount)
testcaseCount += 1
else:
testcaseCount = nextInt() if testcase else 1
for tc in range(testcaseCount):
solve(tc + 1)
assert not tokens
|
continue
|
[{"input": "5\n\n1 1\n\n1\n\n1 2\n\n1 -1\n\n1 4\n\n1 -1 1 -1\n\n3 4\n\n1 -1 -1 -1\n\n-1 1 1 -1\n\n1 1 1 -1\n\n3 4\n\n1 -1 1 1\n\n-1 1 -1 1\n\n1 -1 1 1", "output": ["NO\nYES\nYES\nYES\nNO"]}]
|
block_completion_002517
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
t = int(input())
while(t):
s = input()
d = len(set(s))
for i in range(d, len(s)):
if(s[i] != s[i - d]):
# TODO: Your code here
else:
print("Yes")
t -= 1
|
t = int(input())
while(t):
s = input()
d = len(set(s))
for i in range(d, len(s)):
if(s[i] != s[i - d]):
{{completion}}
else:
print("Yes")
t -= 1
|
print("No")
break
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004807
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
Input Specification: Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
Output Specification: For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Code:
import sys
sys.setrecursionlimit(10000)
def read_line(f):
while True:
s=f.readline().strip()
if s:
return s
def read_list(f):
return [int(x) for x in read_line(f).split()]
def read_tuple(f):
return tuple(read_list(f))
def load_single_case(f):
read_line(f)
return read_list(f),read_list(f)
def load_cases(f):
n=int(f.readline())
cases=[]
for _ in range(n):
yield load_single_case(f)
return cases
def solve(case):
an,bn=case
an=an[::-1]
bn=bn[::-1]
used={}
pa=0
prv=None
for c in bn:
while c not in (an[pa],prv):
if used.get(an[pa],0)<=0:
# TODO: Your code here
used[an[pa]]-=1
pa+=1
if c==an[pa]:
pa+=1
else:
used[prv]=used.get(prv,0)+1
prv=c
return True
def outcome_string(outcome):
return "YES" if outcome else "NO"
def save_outcomes(f, outcomes):
for n,o in enumerate(outcomes):
f.write("{}\n".format( outcome_string(o) ))
def process(path_in=None, path_out=None):
if path_out is None and path_in is not None:
path_out=path_in.rsplit(".",1)[0]+".out"
f_in=open(path_in) if path_in else sys.stdin
f_out=open(path_out,"w") if path_out else sys.stdout
try:
outcomes=[solve(c) for c in load_cases(f_in)]
save_outcomes(f_out, outcomes)
finally:
if path_in:
f_in.close()
if path_out:
f_out.close()
process()
|
import sys
sys.setrecursionlimit(10000)
def read_line(f):
while True:
s=f.readline().strip()
if s:
return s
def read_list(f):
return [int(x) for x in read_line(f).split()]
def read_tuple(f):
return tuple(read_list(f))
def load_single_case(f):
read_line(f)
return read_list(f),read_list(f)
def load_cases(f):
n=int(f.readline())
cases=[]
for _ in range(n):
yield load_single_case(f)
return cases
def solve(case):
an,bn=case
an=an[::-1]
bn=bn[::-1]
used={}
pa=0
prv=None
for c in bn:
while c not in (an[pa],prv):
if used.get(an[pa],0)<=0:
{{completion}}
used[an[pa]]-=1
pa+=1
if c==an[pa]:
pa+=1
else:
used[prv]=used.get(prv,0)+1
prv=c
return True
def outcome_string(outcome):
return "YES" if outcome else "NO"
def save_outcomes(f, outcomes):
for n,o in enumerate(outcomes):
f.write("{}\n".format( outcome_string(o) ))
def process(path_in=None, path_out=None):
if path_out is None and path_in is not None:
path_out=path_in.rsplit(".",1)[0]+".out"
f_in=open(path_in) if path_in else sys.stdin
f_out=open(path_out,"w") if path_out else sys.stdout
try:
outcomes=[solve(c) for c in load_cases(f_in)]
save_outcomes(f_out, outcomes)
finally:
if path_in:
f_in.close()
if path_out:
f_out.close()
process()
|
return False
|
[{"input": "5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1", "output": ["YES\nYES\nNO\nYES\nNO"]}]
|
block_completion_008013
|
block
|
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: You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order: the root has index $$$1$$$; if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way: if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$; otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree: choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.
Output Specification: Print one integer — the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.
Code:
def dfs(tree,i,h):
if # TODO: Your code here:
return [tree[i],1]
ls,li=dfs(tree,i*2+1,h)
rs,ri=dfs(tree,i*2+2,h)
res=li*ri
if ls!=rs:
res*=2
if ls>rs:
return [tree[i]+rs+ls,res]
else:
return [tree[i]+ls+rs,res]
h=int(input())
tree=input()
print(dfs(tree,0,h)[1]%998244353 )
|
def dfs(tree,i,h):
if {{completion}}:
return [tree[i],1]
ls,li=dfs(tree,i*2+1,h)
rs,ri=dfs(tree,i*2+2,h)
res=li*ri
if ls!=rs:
res*=2
if ls>rs:
return [tree[i]+rs+ls,res]
else:
return [tree[i]+ls+rs,res]
h=int(input())
tree=input()
print(dfs(tree,0,h)[1]%998244353 )
|
i>=2**(h-1)-1
|
[{"input": "4\nBAAAAAAAABBABAB", "output": ["16"]}, {"input": "2\nBAA", "output": ["1"]}, {"input": "2\nABA", "output": ["2"]}, {"input": "2\nAAB", "output": ["2"]}, {"input": "2\nAAA", "output": ["1"]}]
|
control_completion_001666
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
Input Specification: The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
Output Specification: For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
Notes: NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 < a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Code:
import sys
input = sys.stdin.readline
def getInts(): return map(int, input().split())
def solve():
input()
a = [*getInts()]
if # TODO: Your code here:
print(len(a) - a.count(0))
else:
s = set(a)
print(len(a) + (len(a) == len(s)))
for _ in range(int(input())):
solve()
|
import sys
input = sys.stdin.readline
def getInts(): return map(int, input().split())
def solve():
input()
a = [*getInts()]
if {{completion}}:
print(len(a) - a.count(0))
else:
s = set(a)
print(len(a) + (len(a) == len(s)))
for _ in range(int(input())):
solve()
|
0 in a
|
[{"input": "3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0", "output": ["4\n3\n2"]}]
|
control_completion_008026
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Kristina has two arrays $$$a$$$ and $$$b$$$, each containing $$$n$$$ non-negative integers. She can perform the following operation on array $$$a$$$ any number of times: apply a decrement to each non-zero element of the array, that is, replace the value of each element $$$a_i$$$ such that $$$a_i > 0$$$ with the value $$$a_i - 1$$$ ($$$1 \le i \le n$$$). If $$$a_i$$$ was $$$0$$$, its value does not change. Determine whether Kristina can get an array $$$b$$$ from an array $$$a$$$ in some number of operations (probably zero). In other words, can she make $$$a_i = b_i$$$ after some number of operations for each $$$1 \le i \le n$$$?For example, let $$$n = 4$$$, $$$a = [3, 5, 4, 1]$$$ and $$$b = [1, 3, 2, 0]$$$. In this case, she can apply the operation twice: after the first application of the operation she gets $$$a = [2, 4, 3, 0]$$$; after the second use of the operation she gets $$$a = [1, 3, 2, 0]$$$. Thus, in two operations, she can get an array $$$b$$$ from an array $$$a$$$.
Input Specification: The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$). The second line of each test case contains exactly $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ non-negative integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, output on a separate line: YES, if by doing some number of operations it is possible to get an array $$$b$$$ from an array $$$a$$$; NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
Notes: NoteThe first test case is analyzed in the statement.In the second test case, it is enough to apply the operation to array $$$a$$$ once.In the third test case, it is impossible to get array $$$b$$$ from array $$$a$$$.
Code:
def solve(a, b):
inf = 2 * 10 ** 6
d, n = inf, len(b)
for i in range(n):
if b[i] > 0:
# TODO: Your code here
# b[i] > a[i]
if d < 0:
print("NO")
return
# All elements of b are 0s
if d == inf:
print("YES")
return
for i in range(n):
if a[i] - b[i] > d:
print("NO")
return
if b[i] > 0 and a[i] - b[i] < d:
print("NO")
return
# all a[i] - b[i] == d
print("YES")
def main():
from sys import stdin
from itertools import islice
tkns = map(int, stdin.read().split())
t = next(tkns)
for T in range(t):
n = next(tkns)
a, b = list(islice(tkns, n)), list(islice(tkns, n))
solve(a, b)
main()
|
def solve(a, b):
inf = 2 * 10 ** 6
d, n = inf, len(b)
for i in range(n):
if b[i] > 0:
{{completion}}
# b[i] > a[i]
if d < 0:
print("NO")
return
# All elements of b are 0s
if d == inf:
print("YES")
return
for i in range(n):
if a[i] - b[i] > d:
print("NO")
return
if b[i] > 0 and a[i] - b[i] < d:
print("NO")
return
# all a[i] - b[i] == d
print("YES")
def main():
from sys import stdin
from itertools import islice
tkns = map(int, stdin.read().split())
t = next(tkns)
for T in range(t):
n = next(tkns)
a, b = list(islice(tkns, n)), list(islice(tkns, n))
solve(a, b)
main()
|
d = min(d, a[i] - b[i])
|
[{"input": "6\n\n4\n\n3 5 4 1\n\n1 3 2 0\n\n3\n\n1 2 1\n\n0 1 0\n\n4\n\n5 3 7 2\n\n1 1 1 1\n\n5\n\n1 2 3 4 5\n\n1 2 3 4 6\n\n1\n\n8\n\n0\n\n1\n\n4\n\n6", "output": ["YES\nYES\nNO\nNO\nYES\nNO"]}]
|
block_completion_003931
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
from collections import defaultdict
ak = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
t = int(input())
for _ in range(t):
count = 0
d = defaultdict(int)
n = int(input())
for i in range(n):
s = input()
for c in ak:
if c != s[0]:
if d[c + s[1]] > 0:
count += d[c + s[1]]
if c != s[1]:
if # TODO: Your code here:
count += d[s[0] + c]
d[s] += 1
print(count)
|
from collections import defaultdict
ak = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
t = int(input())
for _ in range(t):
count = 0
d = defaultdict(int)
n = int(input())
for i in range(n):
s = input()
for c in ak:
if c != s[0]:
if d[c + s[1]] > 0:
count += d[c + s[1]]
if c != s[1]:
if {{completion}}:
count += d[s[0] + c]
d[s] += 1
print(count)
|
d[s[0] + c] > 0
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
control_completion_000870
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. The $$$i$$$-th column has the bottom $$$a_i$$$ cells blocked (the cells in rows $$$1, 2, \dots, a_i$$$), the remaining $$$n - a_i$$$ cells are unblocked.A robot is travelling across this grid. You can send it commands — move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.However, the robot is broken — it executes each received command $$$k$$$ times. So if you tell it to move up, for example, it will move up $$$k$$$ times ($$$k$$$ cells). You can't send it commands while the robot executes the current one.You are asked $$$q$$$ queries about the robot. Each query has a start cell, a finish cell and a value $$$k$$$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times?The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of rows and columns of the grid. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$0 \le a_i \le n$$$) — the number of blocked cells on the bottom of the $$$i$$$-th column. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contain five integers $$$x_s, y_s, x_f, y_f$$$ and $$$k$$$ ($$$a[y_s] < x_s \le n$$$; $$$1 \le y_s \le m$$$; $$$a[y_f] < x_f \le n$$$; $$$1 \le y_f \le m$$$; $$$1 \le k \le 10^9$$$) — the row and the column of the start cell, the row and the column of the finish cell and the number of times each your command is executed. The start and the finish cell of each query are unblocked.
Output Specification: For each query, print "YES" if you can send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times. Otherwise, print "NO".
Code:
input = __import__('sys').stdin.readline
log2s = [0, 0]
for i in range(2, 200005):
log2s.append(log2s[i // 2] + 1)
n, m = map(int, input().split())
sparse = [[0] + list(map(int, input().split()))]
for j in range(20):
sparse.append([max(sparse[j][min(i + (1 << j), m)], sparse[j][i]) for i in range(m+1)])
def getmax(L, R):
j = log2s[R - L + 1]
return max(sparse[j][R - (1 << j) + 1], sparse[j][L])
for _ in range(int(input())):
x1, y1, x2, y2, k = map(int, input().split())
if (x1 - x2) % k != 0 or (y1 - y2) % k != 0:
print('NO')
continue
# i * k + x1 <= n
i = (n - x1) // k
h = i * k + x1
while h > n:
# TODO: Your code here
print('YES' if getmax(min(y1, y2), max(y1, y2)) < h else 'NO')
|
input = __import__('sys').stdin.readline
log2s = [0, 0]
for i in range(2, 200005):
log2s.append(log2s[i // 2] + 1)
n, m = map(int, input().split())
sparse = [[0] + list(map(int, input().split()))]
for j in range(20):
sparse.append([max(sparse[j][min(i + (1 << j), m)], sparse[j][i]) for i in range(m+1)])
def getmax(L, R):
j = log2s[R - L + 1]
return max(sparse[j][R - (1 << j) + 1], sparse[j][L])
for _ in range(int(input())):
x1, y1, x2, y2, k = map(int, input().split())
if (x1 - x2) % k != 0 or (y1 - y2) % k != 0:
print('NO')
continue
# i * k + x1 <= n
i = (n - x1) // k
h = i * k + x1
while h > n:
{{completion}}
print('YES' if getmax(min(y1, y2), max(y1, y2)) < h else 'NO')
|
h -= k
|
[{"input": "11 10\n9 0 0 10 3 4 8 11 10 8\n6\n1 2 1 3 1\n1 2 1 3 2\n4 3 4 5 2\n5 3 11 5 3\n5 3 11 5 2\n11 9 9 10 1", "output": ["YES\nNO\nNO\nNO\nYES\nYES"]}]
|
block_completion_002998
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
Input Specification: The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
Notes: NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
Code:
for _ in [0]*int(input()):
input()
n = list(map(int,input().split()))
s,f,m = 0,0,0
for i in n:
s+=i
if s<0:m = 1;break
if s==0:# TODO: Your code here
if f and s>0:m=1;break
print("YNEOS"[(m or not f)::2])
|
for _ in [0]*int(input()):
input()
n = list(map(int,input().split()))
s,f,m = 0,0,0
for i in n:
s+=i
if s<0:m = 1;break
if s==0:{{completion}}
if f and s>0:m=1;break
print("YNEOS"[(m or not f)::2])
|
f=1
|
[{"input": "7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0", "output": ["No\nYes\nNo\nNo\nYes\nYes\nYes"]}]
|
block_completion_000427
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid with $$$r$$$ rows and $$$c$$$ columns, where the square on the $$$i$$$-th row and $$$j$$$-th column has an integer $$$a_{i, j}$$$ written on it. Initially, all elements are set to $$$0$$$. We are allowed to do the following operation: Choose indices $$$1 \le i \le r$$$ and $$$1 \le j \le c$$$, then replace all values on the same row or column as $$$(i, j)$$$ with the value xor $$$1$$$. In other words, for all $$$a_{x, y}$$$ where $$$x=i$$$ or $$$y=j$$$ or both, replace $$$a_{x, y}$$$ with $$$a_{x, y}$$$ xor $$$1$$$. You want to form grid $$$b$$$ by doing the above operations a finite number of times. However, some elements of $$$b$$$ are missing and are replaced with '?' instead.Let $$$k$$$ be the number of '?' characters. Among all the $$$2^k$$$ ways of filling up the grid $$$b$$$ by replacing each '?' with '0' or '1', count the number of grids, that can be formed by doing the above operation a finite number of times, starting from the grid filled with $$$0$$$. As this number can be large, output it modulo $$$998244353$$$.
Input Specification: The first line contains two integers $$$r$$$ and $$$c$$$ ($$$1 \le r, c \le 2000$$$) — the number of rows and columns of the grid respectively. The $$$i$$$-th of the next $$$r$$$ lines contain $$$c$$$ characters $$$b_{i, 1}, b_{i, 2}, \ldots, b_{i, c}$$$ ($$$b_{i, j} \in \{0, 1, ?\}$$$).
Output Specification: Print a single integer representing the number of ways to fill up grid $$$b$$$ modulo $$$998244353$$$.
Notes: NoteIn the first test case, the only way to fill in the $$$\texttt{?}$$$s is to fill it in as such: 010111010 This can be accomplished by doing a single operation by choosing $$$(i,j)=(2,2)$$$.In the second test case, it can be shown that there is no sequence of operations that can produce that grid.
Code:
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
M = 998244353
r, c = I()
rows = []
for i in range(r):
rows.append([*input()])
if r % 2 == 0 and c % 2 == 0:
blanks = 0
for i in range(r):
blanks += rows[i].count('?')
print(pow(2, blanks, M))
elif r % 2 + c % 2 == 1:
if r % 2 == 1:
nrows = []
for i in range(c):
nrows.append([rows[j][i] for j in range(r)])
rows = nrows
ones = 1
zeroes = 1
for row in rows:
unk = 0
xor = 0
for char in row:
if char == '?':
unk += 1
elif char == '1':
xor = 1 - xor
if unk == 0:
if xor == 1:
zeroes = 0
else:
ones = 0
else:
zeroes = zeroes * pow(2, unk - 1, M) % M
ones = ones * pow(2, unk - 1, M ) % M
print((ones + zeroes) % M)
else:
RC = [0] * (r + c)
edges = [[] for i in range(r + c)]
for i in range(r):
for j in range(c):
char = rows[i][j]
if char == '?':
edges[i].append(j + r)
edges[j + r].append(i)
elif char == '1':
RC[i] = 1 - RC[i]
RC[r + j] = 1 - RC[r + j]
seen = [0] * (r + c)
zeroes = []
ones = []
for i in range(r + c):
if not seen[i]:
component = [i]
seen[i] = 1
j = 0
while j < len(component):
if len(component) == r + c:
break
for v in edges[component[j]]:
if not seen[v]:
# TODO: Your code here
j += 1
n = len(component)
m = 0
x = 0
for v in component:
m += len(edges[v])
x ^= RC[v]
m //= 2
if n % 2 == 0:
if x == 0:
y = pow(2, m - n + 1, M)
zeroes.append(y)
ones.append(y)
else:
print(0)
exit()
else:
y = pow(2, m - n + 1, M)
if x == 0:
zeroes.append(y)
ones.append(0)
else:
ones.append(y)
zeroes.append(0)
zs = 1
for g in zeroes:
zs = zs * g % M
os = 1
for g in ones:
os = os * g % M
print((zs + os) % M)
|
# import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
M = 998244353
r, c = I()
rows = []
for i in range(r):
rows.append([*input()])
if r % 2 == 0 and c % 2 == 0:
blanks = 0
for i in range(r):
blanks += rows[i].count('?')
print(pow(2, blanks, M))
elif r % 2 + c % 2 == 1:
if r % 2 == 1:
nrows = []
for i in range(c):
nrows.append([rows[j][i] for j in range(r)])
rows = nrows
ones = 1
zeroes = 1
for row in rows:
unk = 0
xor = 0
for char in row:
if char == '?':
unk += 1
elif char == '1':
xor = 1 - xor
if unk == 0:
if xor == 1:
zeroes = 0
else:
ones = 0
else:
zeroes = zeroes * pow(2, unk - 1, M) % M
ones = ones * pow(2, unk - 1, M ) % M
print((ones + zeroes) % M)
else:
RC = [0] * (r + c)
edges = [[] for i in range(r + c)]
for i in range(r):
for j in range(c):
char = rows[i][j]
if char == '?':
edges[i].append(j + r)
edges[j + r].append(i)
elif char == '1':
RC[i] = 1 - RC[i]
RC[r + j] = 1 - RC[r + j]
seen = [0] * (r + c)
zeroes = []
ones = []
for i in range(r + c):
if not seen[i]:
component = [i]
seen[i] = 1
j = 0
while j < len(component):
if len(component) == r + c:
break
for v in edges[component[j]]:
if not seen[v]:
{{completion}}
j += 1
n = len(component)
m = 0
x = 0
for v in component:
m += len(edges[v])
x ^= RC[v]
m //= 2
if n % 2 == 0:
if x == 0:
y = pow(2, m - n + 1, M)
zeroes.append(y)
ones.append(y)
else:
print(0)
exit()
else:
y = pow(2, m - n + 1, M)
if x == 0:
zeroes.append(y)
ones.append(0)
else:
ones.append(y)
zeroes.append(0)
zs = 1
for g in zeroes:
zs = zs * g % M
os = 1
for g in ones:
os = os * g % M
print((zs + os) % M)
|
seen[v] = 1
component.append(v)
|
[{"input": "3 3\n?10\n1??\n010", "output": ["1"]}, {"input": "2 3\n000\n001", "output": ["0"]}, {"input": "1 1\n?", "output": ["2"]}, {"input": "6 9\n1101011?0\n001101?00\n101000110\n001011010\n0101?01??\n00?1000?0", "output": ["8"]}]
|
block_completion_008069
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columns — from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$) — the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$) — coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$) — coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$) — subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
input=sys.stdin.readline
R=lambda:map(int,input().split())
n,m=R();r,c,tr,tc=[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
def A(t,i,v):
while i<=n:t[i]+=v;i+=i&(-i)
def Q(t,i):
s=0
while i:s+=t[i];i-=i&(-i)
return s
for _ in range(m):
v=[*R()];op,x,y=v[:3]
if op==1:
r[x]+=1;c[y]+=1
if r[x]==1:A(tr,x,1)
if c[y]==1:A(tc,y,1)
elif op==2:
r[x]-=1;c[y]-=1
if r[x]==0:# TODO: Your code here
if c[y]==0:A(tc,y,-1)
else:
x1,y1=v[3:]
print('Yes' if Q(tr,x1)-Q(tr,x-1)==x1-x+1 or Q(tc,y1)-Q(tc,y-1)==y1-y+1 else 'No')
|
import sys
input=sys.stdin.readline
R=lambda:map(int,input().split())
n,m=R();r,c,tr,tc=[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
def A(t,i,v):
while i<=n:t[i]+=v;i+=i&(-i)
def Q(t,i):
s=0
while i:s+=t[i];i-=i&(-i)
return s
for _ in range(m):
v=[*R()];op,x,y=v[:3]
if op==1:
r[x]+=1;c[y]+=1
if r[x]==1:A(tr,x,1)
if c[y]==1:A(tc,y,1)
elif op==2:
r[x]-=1;c[y]-=1
if r[x]==0:{{completion}}
if c[y]==0:A(tc,y,-1)
else:
x1,y1=v[3:]
print('Yes' if Q(tr,x1)-Q(tr,x-1)==x1-x+1 or Q(tc,y1)-Q(tc,y-1)==y1-y+1 else 'No')
|
A(tr,x,-1)
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005571
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$. Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the initial levels of trees moisture. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.
Output Specification: For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.
Notes: NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.
Code:
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();d=[a[0]]
for i in range(1,n):d.append(a[i]-a[i-1])
for i in range(1,n):
if d[i]<=0:# TODO: Your code here
print(sum(abs(i) for i in d))
|
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();d=[a[0]]
for i in range(1,n):d.append(a[i]-a[i-1])
for i in range(1,n):
if d[i]<=0:{{completion}}
print(sum(abs(i) for i in d))
|
d[0]+=d[i]
|
[{"input": "4\n3\n-2 -2 -2\n3\n10 4 7\n4\n4 -4 4 -4\n5\n1 -2 3 -4 5", "output": ["2\n13\n36\n33"]}]
|
block_completion_004199
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i > 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i < i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty): Choose a card $$$x$$$ such that no other cards are hanging onto it. Append the number written on card $$$x$$$ to the end of $$$s$$$. If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$. Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) describing which card that each card hangs onto.
Output Specification: Print a single integer — the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.
Notes: NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order: Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 > w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$. Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$. Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$. Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 > w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$. Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$. Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.
Code:
mod = 998244353
def main():
import sys
input = sys.stdin.readline
N = int(input())
P = [0, 0] + list(map(int, input().split()))
child = [[] for _ in range(N + 1)]
for v in range(2, N+1):
p = P[v]
child[p].append(v)
dp = [0] * (N + 1)
dp2 = [0] * (N + 1)
for v in range(N, 0, -1):
if not child[v]:
dp2[v] = 1
dp[v] = 1
else:
S = 0
D = 0
for c in child[v]:
# TODO: Your code here
dp2[v] = D + 1
dp[v] = max(S, D + 1)
print(dp[1])
#print(dp, dp2)
if __name__ == '__main__':
main()
|
mod = 998244353
def main():
import sys
input = sys.stdin.readline
N = int(input())
P = [0, 0] + list(map(int, input().split()))
child = [[] for _ in range(N + 1)]
for v in range(2, N+1):
p = P[v]
child[p].append(v)
dp = [0] * (N + 1)
dp2 = [0] * (N + 1)
for v in range(N, 0, -1):
if not child[v]:
dp2[v] = 1
dp[v] = 1
else:
S = 0
D = 0
for c in child[v]:
{{completion}}
dp2[v] = D + 1
dp[v] = max(S, D + 1)
print(dp[1])
#print(dp, dp2)
if __name__ == '__main__':
main()
|
S += dp[c]
D = max(D, dp2[c])
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004725
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. The $$$i$$$-th column has the bottom $$$a_i$$$ cells blocked (the cells in rows $$$1, 2, \dots, a_i$$$), the remaining $$$n - a_i$$$ cells are unblocked.A robot is travelling across this grid. You can send it commands — move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.However, the robot is broken — it executes each received command $$$k$$$ times. So if you tell it to move up, for example, it will move up $$$k$$$ times ($$$k$$$ cells). You can't send it commands while the robot executes the current one.You are asked $$$q$$$ queries about the robot. Each query has a start cell, a finish cell and a value $$$k$$$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times?The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of rows and columns of the grid. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$0 \le a_i \le n$$$) — the number of blocked cells on the bottom of the $$$i$$$-th column. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contain five integers $$$x_s, y_s, x_f, y_f$$$ and $$$k$$$ ($$$a[y_s] < x_s \le n$$$; $$$1 \le y_s \le m$$$; $$$a[y_f] < x_f \le n$$$; $$$1 \le y_f \le m$$$; $$$1 \le k \le 10^9$$$) — the row and the column of the start cell, the row and the column of the finish cell and the number of times each your command is executed. The start and the finish cell of each query are unblocked.
Output Specification: For each query, print "YES" if you can send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times. Otherwise, print "NO".
Code:
from sys import setrecursionlimit, stdin
readline = stdin.readline
# def I(): return int(readline())
# def ST(): return readline()[:-1]
# def LI(): return list(map(int, readline().split()))
def solve():
N, m = map(int, readline().split())
A = [0] + list(map(int, readline().split()))
n = len(A)
num = 1 << (n - 1).bit_length()
tree = [0] * 2 * num
for i in range(n):
tree[num + i] = A[i]
for i in range(num - 1, 0, -1):
tree[i] = max(tree[2 * i], tree[2 * i + 1])
def query(l, r):
ret = 0
l += num
r += num
while l < r:
if # TODO: Your code here:
ret = max(ret, tree[l])
l += 1
if r & 1:
ret = max(ret, tree[r - 1])
l >>= 1
r >>= 1
return ret
for _ in range(int(input())):
sx, sy, gx, gy, k = map(int, readline().split())
dx = abs(sx - gx)
dy = abs(sy - gy)
if dx % k or dy % k:
print("NO")
continue
top = sx + k * ((N - sx) // k)
if sy > gy: sy, gy = gy, sy
if query(sy, gy + 1) < top: print("YES")
else: print("NO")
solve()
|
from sys import setrecursionlimit, stdin
readline = stdin.readline
# def I(): return int(readline())
# def ST(): return readline()[:-1]
# def LI(): return list(map(int, readline().split()))
def solve():
N, m = map(int, readline().split())
A = [0] + list(map(int, readline().split()))
n = len(A)
num = 1 << (n - 1).bit_length()
tree = [0] * 2 * num
for i in range(n):
tree[num + i] = A[i]
for i in range(num - 1, 0, -1):
tree[i] = max(tree[2 * i], tree[2 * i + 1])
def query(l, r):
ret = 0
l += num
r += num
while l < r:
if {{completion}}:
ret = max(ret, tree[l])
l += 1
if r & 1:
ret = max(ret, tree[r - 1])
l >>= 1
r >>= 1
return ret
for _ in range(int(input())):
sx, sy, gx, gy, k = map(int, readline().split())
dx = abs(sx - gx)
dy = abs(sy - gy)
if dx % k or dy % k:
print("NO")
continue
top = sx + k * ((N - sx) // k)
if sy > gy: sy, gy = gy, sy
if query(sy, gy + 1) < top: print("YES")
else: print("NO")
solve()
|
l & 1
|
[{"input": "11 10\n9 0 0 10 3 4 8 11 10 8\n6\n1 2 1 3 1\n1 2 1 3 2\n4 3 4 5 2\n5 3 11 5 3\n5 3 11 5 2\n11 9 9 10 1", "output": ["YES\nNO\nNO\nNO\nYES\nYES"]}]
|
control_completion_002945
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v < \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v < \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
Output Specification: Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
Notes: NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Code:
from collections import deque
I=lambda:map(int,input().split())
n,m=I()
g=[[]for _ in range(n)]
din,dout,dcur=[0]*n,[0]*n,[0]*n
for _ in range(m):
u,v=I()
u,v=u-1,v-1
g[u].append(v)
dout[u]+=1;din[v]+=1;dcur[v]+=1
q=deque([i for i,d in enumerate(din) if d==0])
f=[1]*n
while q:
u=q.popleft()
for v in g[u]:
if dout[u]>1 and din[v]>1:
f[v]=max(f[v],f[u]+1)
dcur[v]-=1
if dcur[v]==0:# TODO: Your code here
print(max(f))
|
from collections import deque
I=lambda:map(int,input().split())
n,m=I()
g=[[]for _ in range(n)]
din,dout,dcur=[0]*n,[0]*n,[0]*n
for _ in range(m):
u,v=I()
u,v=u-1,v-1
g[u].append(v)
dout[u]+=1;din[v]+=1;dcur[v]+=1
q=deque([i for i,d in enumerate(din) if d==0])
f=[1]*n
while q:
u=q.popleft()
for v in g[u]:
if dout[u]>1 and din[v]>1:
f[v]=max(f[v],f[u]+1)
dcur[v]-=1
if dcur[v]==0:{{completion}}
print(max(f))
|
q.append(v)
|
[{"input": "3 3\n1 2\n2 3\n1 3", "output": ["2"]}, {"input": "5 0", "output": ["1"]}, {"input": "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3", "output": ["3"]}]
|
block_completion_007896
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array $$$[1, 1, 1]$$$ is $$$1$$$; $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$; $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.
Input Specification: In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).
Output Specification: Print the answer to each query on a new line.
Notes: NoteAfter the first query $$$a$$$ is equal to $$$[1, 2, 2, 4, 5]$$$, and the answer is $$$29$$$ because we can split each of the subsegments the following way: $$$[1; 1]$$$: $$$[1]$$$, 1 block; $$$[1; 2]$$$: $$$[1] + [2]$$$, 2 blocks; $$$[1; 3]$$$: $$$[1] + [2, 2]$$$, 2 blocks; $$$[1; 4]$$$: $$$[1] + [2, 2] + [4]$$$, 3 blocks; $$$[1; 5]$$$: $$$[1] + [2, 2] + [4] + [5]$$$, 4 blocks; $$$[2; 2]$$$: $$$[2]$$$, 1 block; $$$[2; 3]$$$: $$$[2, 2]$$$, 1 block; $$$[2; 4]$$$: $$$[2, 2] + [4]$$$, 2 blocks; $$$[2; 5]$$$: $$$[2, 2] + [4] + [5]$$$, 3 blocks; $$$[3; 3]$$$: $$$[2]$$$, 1 block; $$$[3; 4]$$$: $$$[2] + [4]$$$, 2 blocks; $$$[3; 5]$$$: $$$[2] + [4] + [5]$$$, 3 blocks; $$$[4; 4]$$$: $$$[4]$$$, 1 block; $$$[4; 5]$$$: $$$[4] + [5]$$$, 2 blocks; $$$[5; 5]$$$: $$$[5]$$$, 1 block; which is $$$1 + 2 + 2 + 3 + 4 + 1 + 1 + 2 + 3 + 1 + 2 + 3 + 1 + 2 + 1 = 29$$$ in total.
Code:
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.insert(0, 0)
a.append(0)
ans = 0
for # TODO: Your code here:
ans += (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i
while(m):
i, x = map(int, input().split())
ans -= (a[i] != a[i - 1]) * (n - i + 1) * (i - 1)
ans -= (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i
a[i] = x
ans += (a[i] != a[i - 1]) * (n - i + 1) * (i - 1)
ans += (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i
print(ans + n * (n + 1) // 2)
m -= 1
|
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.insert(0, 0)
a.append(0)
ans = 0
for {{completion}}:
ans += (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i
while(m):
i, x = map(int, input().split())
ans -= (a[i] != a[i - 1]) * (n - i + 1) * (i - 1)
ans -= (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i
a[i] = x
ans += (a[i] != a[i - 1]) * (n - i + 1) * (i - 1)
ans += (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i
print(ans + n * (n + 1) // 2)
m -= 1
|
i in range(1, n + 1)
|
[{"input": "5 5\n1 2 3 4 5\n3 2\n4 2\n3 1\n2 1\n2 2", "output": ["29\n23\n35\n25\n35"]}]
|
control_completion_000079
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) — the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
import sys
class LCA:
def __init__(self, g, root=0):
self.g = g
self.root = root
n = len(g)
self.logn = (n - 1).bit_length()
self.depth = [None] * n
self.parent = [[None] * self.logn for _ in range(n)]
self._dfs()
self._doubling()
def _dfs(self):
self.depth[self.root] = 0
stack = [self.root]
while stack:
u = stack.pop()
for v in self.g[u]:
if self.depth[v] is None:
self.depth[v] = self.depth[u] + 1
self.parent[v][0] = u
stack.append(v)
def _doubling(self):
for i in range(self.logn - 1):
for p in self.parent:
if p[i] is not None:
# TODO: Your code here
def lca(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
d = self.depth[v] - self.depth[u]
for i in range(d.bit_length()):
if d >> i & 1:
v = self.parent[v][i]
if u == v:
return u
for i in reversed(range(self.logn)):
if (pu := self.parent[u][i]) != (pv := self.parent[v][i]):
u, v = pu, pv
return self.parent[u][i]
def query(lca):
k = int(sys.stdin.readline())
p = sorted(
(int(x) - 1 for x in sys.stdin.readline().split()),
key=lca.depth.__getitem__,
reverse=True,
)
branch = []
top = p[0]
for x in p[1:]:
if lca.lca(top, x) == x:
top = x
else:
branch.append(x)
if not branch:
return True
if lca.lca(branch[0], p[0]) != lca.lca(branch[0], top):
return False
for i in range(1, len(branch)):
if lca.lca(branch[i - 1], branch[i]) != branch[i]:
return False
return True
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = (int(x) - 1 for x in sys.stdin.readline().split())
g[u].append(v)
g[v].append(u)
lca = LCA(g)
for _ in range(int(input())):
print("YES" if query(lca) else "NO")
|
import sys
class LCA:
def __init__(self, g, root=0):
self.g = g
self.root = root
n = len(g)
self.logn = (n - 1).bit_length()
self.depth = [None] * n
self.parent = [[None] * self.logn for _ in range(n)]
self._dfs()
self._doubling()
def _dfs(self):
self.depth[self.root] = 0
stack = [self.root]
while stack:
u = stack.pop()
for v in self.g[u]:
if self.depth[v] is None:
self.depth[v] = self.depth[u] + 1
self.parent[v][0] = u
stack.append(v)
def _doubling(self):
for i in range(self.logn - 1):
for p in self.parent:
if p[i] is not None:
{{completion}}
def lca(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
d = self.depth[v] - self.depth[u]
for i in range(d.bit_length()):
if d >> i & 1:
v = self.parent[v][i]
if u == v:
return u
for i in reversed(range(self.logn)):
if (pu := self.parent[u][i]) != (pv := self.parent[v][i]):
u, v = pu, pv
return self.parent[u][i]
def query(lca):
k = int(sys.stdin.readline())
p = sorted(
(int(x) - 1 for x in sys.stdin.readline().split()),
key=lca.depth.__getitem__,
reverse=True,
)
branch = []
top = p[0]
for x in p[1:]:
if lca.lca(top, x) == x:
top = x
else:
branch.append(x)
if not branch:
return True
if lca.lca(branch[0], p[0]) != lca.lca(branch[0], top):
return False
for i in range(1, len(branch)):
if lca.lca(branch[i - 1], branch[i]) != branch[i]:
return False
return True
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = (int(x) - 1 for x in sys.stdin.readline().split())
g[u].append(v)
g[v].append(u)
lca = LCA(g)
for _ in range(int(input())):
print("YES" if query(lca) else "NO")
|
p[i + 1] = self.parent[p[i]][i]
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
block_completion_002289
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Today, like every year at SWERC, the $$$n^2$$$ contestants have gathered outside the venue to take a drone photo. Jennifer, the social media manager for the event, has arranged them into an $$$n\times n$$$ square. Being very good at her job, she knows that the contestant standing on the intersection of the $$$i$$$-th row with the $$$j$$$-th column is $$$a_{i,j}$$$ years old. Coincidentally, she notices that no two contestants have the same age, and that everyone is between $$$1$$$ and $$$n^2$$$ years old.Jennifer is planning to have some contestants hold a banner with the ICPC logo parallel to the ground, so that it is clearly visible in the aerial picture. Here are the steps that she is going to follow in order to take the perfect SWERC drone photo. First of all, Jennifer is going to select four contestants standing on the vertices of an axis-aligned rectangle. Then, she will have the two younger contestants hold one of the poles, while the two older contestants will hold the other pole. Finally, she will unfold the banner, using the poles to support its two ends. Obviously, this can only be done if the two poles are parallel and do not cross, as shown in the pictures below. Being very indecisive, Jennifer would like to try out all possible arrangements for the banner, but she is worried that this may cause the contestants to be late for the competition. How many different ways are there to choose the four contestants holding the poles in order to take a perfect photo? Two choices are considered different if at least one contestant is included in one but not the other.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2\le n \le 1500$$$). The next $$$n$$$ lines describe the ages of the contestants. Specifically, the $$$i$$$-th line contains the integers $$$a_{i,1},a_{i,2},\ldots,a_{i,n}$$$ ($$$1\le a_{i,j}\le n^2$$$). It is guaranteed that $$$a_{i,j}\neq a_{k,l}$$$ if $$$i\neq k$$$ or $$$j\neq l$$$.
Output Specification: Print the number of ways for Jennifer to choose the four contestants holding the poles.
Notes: NoteIn the first sample, there are $$$4$$$ contestants, arranged as follows. There is only one way to choose four contestants, with one pole held by contestants aged $$$1$$$ and $$$2$$$ and the other one by contestants aged $$$3$$$ and $$$4$$$. But then, as we can see in the picture, the poles cross. Since there is no valid way to choose four contestants, the answer is $$$0$$$.In the second sample, the $$$4$$$ contestants are arranged as follows. Once again, there is only one way to choose four contestants, but this time the poles don't cross. Therefore, the answer is $$$1$$$.In the third sample, the $$$9$$$ contestants are arranged as follows. There are $$$6$$$ ways of choosing four contestants so that the poles don't cross, as shown in the following pictures.
Code:
import sys
import random
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
N = int(input())
As = [list(map(int, input().split())) for _ in range(N)]
# N = 1500
# As = list(range(1, N ** 2 + 1))
# random.shuffle(As)
# As = [As[i * N:(i + 1) * N] for i in range(N)]
ijs = [0] * (N ** 2)
for i in range(N):
for # TODO: Your code here:
ijs[As[i][j] - 1] = (i, j)
answer = 0
row_sum = [0] * N
col_sum = [0] * N
for i, j in ijs:
l_row = row_sum[i]
g_row = N - 1 - row_sum[i]
l_col = col_sum[j]
g_col = N - 1 - col_sum[j]
answer += l_col * g_row + g_col * l_row
row_sum[i] += 1
col_sum[j] += 1
assert answer % 2 == 0
print(answer // 2)
|
import sys
import random
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
N = int(input())
As = [list(map(int, input().split())) for _ in range(N)]
# N = 1500
# As = list(range(1, N ** 2 + 1))
# random.shuffle(As)
# As = [As[i * N:(i + 1) * N] for i in range(N)]
ijs = [0] * (N ** 2)
for i in range(N):
for {{completion}}:
ijs[As[i][j] - 1] = (i, j)
answer = 0
row_sum = [0] * N
col_sum = [0] * N
for i, j in ijs:
l_row = row_sum[i]
g_row = N - 1 - row_sum[i]
l_col = col_sum[j]
g_col = N - 1 - col_sum[j]
answer += l_col * g_row + g_col * l_row
row_sum[i] += 1
col_sum[j] += 1
assert answer % 2 == 0
print(answer // 2)
|
j in range(N)
|
[{"input": "2\n1 3\n4 2", "output": ["0"]}, {"input": "2\n3 2\n4 1", "output": ["1"]}, {"input": "3\n9 2 4\n1 5 3\n7 8 6", "output": ["6"]}]
|
control_completion_001072
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \leq i \leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \leq i \leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)?
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array $$$a$$$.
Output Specification: Print a single integer, the minimum number of moves to make $$$b$$$ increasing.
Notes: NoteExample $$$1$$$: you can subtract $$$a_1$$$ from $$$b_1$$$, and add $$$a_3$$$, $$$a_4$$$, and $$$a_5$$$ to $$$b_3$$$, $$$b_4$$$, and $$$b_5$$$ respectively. The final array will be [$$$-1$$$, $$$0$$$, $$$3$$$, $$$4$$$, $$$5$$$] after $$$4$$$ moves.Example $$$2$$$: you can reach [$$$-3$$$, $$$-2$$$, $$$-1$$$, $$$0$$$, $$$1$$$, $$$2$$$, $$$3$$$] in $$$10$$$ moves.
Code:
from math import ceil
n=int(input())
a=list(map(int,input().split()))
ans=float("inf")
for i in range(len(a)):
t=[0]*n
temp=0
j=i-1
prev =0
while j>=0:
x=(ceil((prev+1)/a[j]))
temp+=x
prev=(a[j]*x)
j-=1
k=i+1
prev=0
while # TODO: Your code here:
x=(ceil((prev+1)/a[k]))
temp+=x
prev=(a[k]*x)
k+=1
ans=min(ans,temp)
print(int(ans))
|
from math import ceil
n=int(input())
a=list(map(int,input().split()))
ans=float("inf")
for i in range(len(a)):
t=[0]*n
temp=0
j=i-1
prev =0
while j>=0:
x=(ceil((prev+1)/a[j]))
temp+=x
prev=(a[j]*x)
j-=1
k=i+1
prev=0
while {{completion}}:
x=(ceil((prev+1)/a[k]))
temp+=x
prev=(a[k]*x)
k+=1
ans=min(ans,temp)
print(int(ans))
|
k<len(a)
|
[{"input": "5\n1 2 3 4 5", "output": ["4"]}, {"input": "7\n1 2 1 2 1 2 1", "output": ["10"]}, {"input": "8\n1 8 2 7 3 6 4 5", "output": ["16"]}]
|
control_completion_000963
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You found a map of a weirdly shaped labyrinth. The map is a grid, consisting of $$$n$$$ rows and $$$n$$$ columns. The rows of the grid are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns of the grid are numbered from $$$1$$$ to $$$n$$$ from left to right.The labyrinth has $$$n$$$ layers. The first layer is the bottom left corner (cell $$$(1, 1)$$$). The second layer consists of all cells that are in the grid and adjacent to the first layer by a side or a corner. The third layer consists of all cells that are in the grid and adjacent to the second layer by a side or a corner. And so on. The labyrinth with $$$5$$$ layers, for example, is shaped as follows: The layers are separated from one another with walls. However, there are doors in these walls.Each layer (except for layer $$$n$$$) has exactly two doors to the next layer. One door is placed on the top wall of the layer and another door is placed on the right wall of the layer. For each layer from $$$1$$$ to $$$n-1$$$ you are given positions of these two doors. The doors can be passed in both directions: either from layer $$$i$$$ to layer $$$i+1$$$ or from layer $$$i+1$$$ to layer $$$i$$$.If you are standing in some cell, you can move to an adjacent by a side cell if a wall doesn't block your move (e.g. you can't move to a cell in another layer if there is no door between the cells).Now you have $$$m$$$ queries of sort: what's the minimum number of moves one has to make to go from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of layers in the labyrinth. The $$$i$$$-th of the next $$$n-1$$$ lines contains four integers $$$d_{1,x}, d_{1,y}, d_{2,x}$$$ and $$$d_{2,y}$$$ ($$$1 \le d_{1,x}, d_{1,y}, d_{2,x}, d_{2,y} \le n$$$) — the coordinates of the doors. Both cells are on the $$$i$$$-th layer. The first cell is adjacent to the top wall of the $$$i$$$-th layer by a side — that side is where the door is. The second cell is adjacent to the right wall of the $$$i$$$-th layer by a side — that side is where the door is. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of queries. The $$$j$$$-th of the next $$$m$$$ lines contains four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ ($$$1 \le x_1, y_1, x_2, y_2 \le n$$$) — the coordinates of the cells in the $$$j$$$-th query.
Output Specification: For each query, print a single integer — the minimum number of moves one has to make to go from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$.
Notes: NoteHere is the map of the labyrinth from the second example. The doors are marked red.
Code:
import sys
input = sys.stdin.readline
N = int(input())
logN = (N - 2).bit_length()
door = []
for _ in range(N - 1):
_, a, b, _ = map(int, input().split())
door.append([a - 1, b - 1])
# door = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N - 1)]
dist = [[[-1] * 4 for _ in range(logN)] for _ in range(N - 2)]
'''
0: 0->0
1: 0->1
2: 1->0
3: 1->1
'''
for i in range(N - 2):
d1 = abs(i - door[i][1]) + abs(door[i][0] - i)
dist[i][0][0] = abs(door[i][0] - door[i + 1][0]) + 1
dist[i][0][3] = abs(door[i][1] - door[i + 1][1]) + 1
dist[i][0][1] = min(
abs(i + 1 - door[i + 1][1]) + abs(door[i][0] - (i + 1)) + 1,
d1 + dist[i][0][3]
)
dist[i][0][2] = min(
abs(door[i][1] - (i + 1)) + abs(i + 1 - door[i + 1][0]) + 1,
d1 + dist[i][0][0]
)
for j in range(1, logN):
k = 1 << (j - 1)
for i in range(N - 1 - (1 << j)):
for fr in range(2):
for to in range(2):
# TODO: Your code here
Q = int(input())
for _ in range(Q):
h1, w1, h2, w2 = map(lambda x: int(x) - 1, input().split())
l1 = max(h1, w1)
l2 = max(h2, w2)
if l1 == l2:
print(abs(h1 - h2) + abs(w1 - w2))
continue
if l1 > l2:
l1, l2 = l2, l1
h1, w1, h2, w2 = h2, w2, h1, w1
now = l1
l = l2 - l1 - 1
d0 = abs(h1 - now) + abs(w1 - door[now][0])
d1 = abs(h1 - door[now][1]) + abs(w1 - now)
for i in range(logN - 1, -1, -1):
if l >> i & 1:
d0, d1 = min(d0 + dist[now][i][0], d1 + dist[now][i][2]), min(d0 + dist[now][i][1], d1 + dist[now][i][3])
now += 1 << i
print(min(d0 + abs(now + 1 - h2) + abs(door[now][0] - w2), d1 + abs(door[now][1] - h2) + abs(now + 1 - w2)) + 1)
|
import sys
input = sys.stdin.readline
N = int(input())
logN = (N - 2).bit_length()
door = []
for _ in range(N - 1):
_, a, b, _ = map(int, input().split())
door.append([a - 1, b - 1])
# door = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N - 1)]
dist = [[[-1] * 4 for _ in range(logN)] for _ in range(N - 2)]
'''
0: 0->0
1: 0->1
2: 1->0
3: 1->1
'''
for i in range(N - 2):
d1 = abs(i - door[i][1]) + abs(door[i][0] - i)
dist[i][0][0] = abs(door[i][0] - door[i + 1][0]) + 1
dist[i][0][3] = abs(door[i][1] - door[i + 1][1]) + 1
dist[i][0][1] = min(
abs(i + 1 - door[i + 1][1]) + abs(door[i][0] - (i + 1)) + 1,
d1 + dist[i][0][3]
)
dist[i][0][2] = min(
abs(door[i][1] - (i + 1)) + abs(i + 1 - door[i + 1][0]) + 1,
d1 + dist[i][0][0]
)
for j in range(1, logN):
k = 1 << (j - 1)
for i in range(N - 1 - (1 << j)):
for fr in range(2):
for to in range(2):
{{completion}}
Q = int(input())
for _ in range(Q):
h1, w1, h2, w2 = map(lambda x: int(x) - 1, input().split())
l1 = max(h1, w1)
l2 = max(h2, w2)
if l1 == l2:
print(abs(h1 - h2) + abs(w1 - w2))
continue
if l1 > l2:
l1, l2 = l2, l1
h1, w1, h2, w2 = h2, w2, h1, w1
now = l1
l = l2 - l1 - 1
d0 = abs(h1 - now) + abs(w1 - door[now][0])
d1 = abs(h1 - door[now][1]) + abs(w1 - now)
for i in range(logN - 1, -1, -1):
if l >> i & 1:
d0, d1 = min(d0 + dist[now][i][0], d1 + dist[now][i][2]), min(d0 + dist[now][i][1], d1 + dist[now][i][3])
now += 1 << i
print(min(d0 + abs(now + 1 - h2) + abs(door[now][0] - w2), d1 + abs(door[now][1] - h2) + abs(now + 1 - w2)) + 1)
|
dist[i][j][fr << 1 | to] = min(
dist[i][j - 1][fr << 1] + dist[i + k][j - 1][to],
dist[i][j - 1][fr << 1 | 1] + dist[i + k][j - 1][2 | to]
)
|
[{"input": "2\n1 1 1 1\n10\n1 1 1 1\n1 1 1 2\n1 1 2 1\n1 1 2 2\n1 2 1 2\n1 2 2 1\n1 2 2 2\n2 1 2 1\n2 1 2 2\n2 2 2 2", "output": ["0\n1\n1\n2\n0\n2\n1\n0\n1\n0"]}, {"input": "4\n1 1 1 1\n2 1 2 2\n3 2 1 3\n5\n2 4 4 3\n4 4 3 3\n1 2 3 3\n2 2 4 4\n1 4 2 3", "output": ["3\n4\n3\n6\n2"]}]
|
block_completion_001953
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$) — the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.
Output Specification: Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.
Code:
_,(*a,),*r=(map(int,s.split())for s in open(0))
b=[[0],[0]]
for x in b:
for # TODO: Your code here:x+=x[-1]+max(0,u-v),
max=min
for s,t in r:l=b[s>t];print(l[t]-l[s])
|
_,(*a,),*r=(map(int,s.split())for s in open(0))
b=[[0],[0]]
for x in b:
for {{completion}}:x+=x[-1]+max(0,u-v),
max=min
for s,t in r:l=b[s>t];print(l[t]-l[s])
|
u,v in zip([0]+a,a)
|
[{"input": "7 6\n10 8 9 6 8 12 7\n1 2\n1 7\n4 6\n7 1\n3 5\n4 2", "output": ["2\n10\n0\n7\n3\n1"]}]
|
control_completion_002890
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
t=int(input())
for p in range(t):
l=[]
c=0
a=['R','R','R','R','R','R','R','R']
while(len(l)<8):
s=input()
if # TODO: Your code here:
l.append([*s])
for i in range(8):
if l[i]==a:
c=1
break
print("B" if c!=1 else "R")
|
t=int(input())
for p in range(t):
l=[]
c=0
a=['R','R','R','R','R','R','R','R']
while(len(l)<8):
s=input()
if {{completion}}:
l.append([*s])
for i in range(8):
if l[i]==a:
c=1
break
print("B" if c!=1 else "R")
|
len(s)==8
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
control_completion_005703
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $$$5$$$ players in one team for each match). There are $$$N$$$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $$$i$$$-th candidate player has a power of $$$P_i$$$.Pak Chanek will form zero or more teams from the $$$N$$$ candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of $$$D$$$. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is strictly greater than $$$D$$$.One of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.Determine the maximum number of wins that can be achieved by Pak Chanek.
Input Specification: The first line contains two integers $$$N$$$ and $$$D$$$ ($$$1 \le N \le 10^5$$$, $$$1 \le D \le 10^9$$$) — the number of candidate players and the power of the enemy team. The second line contains $$$N$$$ integers $$$P_1, P_2, \ldots, P_N$$$ ($$$1 \le P_i \le 10^9$$$) — the powers of all candidate players.
Output Specification: A line containing an integer representing the maximum number of wins that can be achieved by Pak Chanek.
Notes: NoteThe $$$1$$$-st team formed is a team containing players $$$4$$$ and $$$6$$$. The power of each player in the team becomes $$$100$$$. So the total power of the team is $$$100 + 100 = 200 > 180$$$.The $$$2$$$-nd team formed is a team containing players $$$1$$$, $$$2$$$, and $$$5$$$. The power of each player in the team becomes $$$90$$$. So the total power of the team is $$$90 + 90 + 90 = 270 > 180$$$.
Code:
import sys,math
n,team=map(int,sys.stdin.readline().split())
arr=sorted(map(int,sys.stdin.readline().split()),reverse=True)
# print(arr)
all=n+1
count=0
for i in range(n):
sub=int(math.floor(team/arr[i])+1)
all-=sub
if # TODO: Your code here:
count+=1
else:break
print(count)
|
import sys,math
n,team=map(int,sys.stdin.readline().split())
arr=sorted(map(int,sys.stdin.readline().split()),reverse=True)
# print(arr)
all=n+1
count=0
for i in range(n):
sub=int(math.floor(team/arr[i])+1)
all-=sub
if {{completion}}:
count+=1
else:break
print(count)
|
all>0
|
[{"input": "6 180\n90 80 70 60 50 100", "output": ["2"]}]
|
control_completion_003666
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a board with $$$n$$$ rows and $$$n$$$ columns, numbered from $$$1$$$ to $$$n$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$.A half-queen attacks cells in the same row, same column, and on one diagonal. More formally, a half-queen on $$$(a, b)$$$ attacks the cell $$$(c, d)$$$ if $$$a=c$$$ or $$$b=d$$$ or $$$a-b=c-d$$$. The blue cells are under attack. What is the minimum number of half-queens that can be placed on that board so as to ensure that each square is attacked by at least one half-queen?Construct an optimal solution.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of the board.
Output Specification: In the first line print a single integer $$$k$$$ — the minimum number of half-queens. In each of the next $$$k$$$ lines print two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the position of the $$$i$$$-th half-queen. If there are multiple solutions, print any.
Notes: NoteExample $$$1$$$: one half-queen is enough. Note: a half-queen on $$$(1, 1)$$$ attacks $$$(1, 1)$$$.Example $$$2$$$: one half-queen is enough too. $$$(1, 2)$$$ or $$$(2, 1)$$$ would be wrong solutions, because a half-queen on $$$(1, 2)$$$ does not attack the cell $$$(2, 1)$$$ and vice versa. $$$(2, 2)$$$ is also a valid solution.Example $$$3$$$: it is impossible to cover the board with one half queen. There are multiple solutions for $$$2$$$ half-queens; you can print any of them.
Code:
import sys
input = sys.stdin.readline
n = int(input())
ans = []
if n <= 2:
k = 1
ans.append(" ".join(map(str, (1, 1))))
elif n == 3:
k = 2
ans.append(" ".join(map(str, (1, 1))))
ans.append(" ".join(map(str, (1, 2))))
else:
for i in range(100000, -1, -1):
if 3 * i + 2 <= n:
# TODO: Your code here
z = 1
for i in range(x):
ans.append(" ".join(map(str, (z + x - i - 1, z + i))))
z += x
x += 1
for i in range(x):
ans.append(" ".join(map(str, (z + x - i - 1, z + i))))
z += x
for i in range((n - 2) % 3):
ans.append(" ".join(map(str, (z + (n - 2) % 3 - i - 1, z + i))))
k = len(ans)
print(k)
sys.stdout.write("\n".join(ans))
|
import sys
input = sys.stdin.readline
n = int(input())
ans = []
if n <= 2:
k = 1
ans.append(" ".join(map(str, (1, 1))))
elif n == 3:
k = 2
ans.append(" ".join(map(str, (1, 1))))
ans.append(" ".join(map(str, (1, 2))))
else:
for i in range(100000, -1, -1):
if 3 * i + 2 <= n:
{{completion}}
z = 1
for i in range(x):
ans.append(" ".join(map(str, (z + x - i - 1, z + i))))
z += x
x += 1
for i in range(x):
ans.append(" ".join(map(str, (z + x - i - 1, z + i))))
z += x
for i in range((n - 2) % 3):
ans.append(" ".join(map(str, (z + (n - 2) % 3 - i - 1, z + i))))
k = len(ans)
print(k)
sys.stdout.write("\n".join(ans))
|
x = i
break
|
[{"input": "1", "output": ["1\n1 1"]}, {"input": "2", "output": ["1\n1 1"]}, {"input": "3", "output": ["2\n1 1\n1 2"]}]
|
block_completion_001073
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. The $$$i$$$-th column has the bottom $$$a_i$$$ cells blocked (the cells in rows $$$1, 2, \dots, a_i$$$), the remaining $$$n - a_i$$$ cells are unblocked.A robot is travelling across this grid. You can send it commands — move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.However, the robot is broken — it executes each received command $$$k$$$ times. So if you tell it to move up, for example, it will move up $$$k$$$ times ($$$k$$$ cells). You can't send it commands while the robot executes the current one.You are asked $$$q$$$ queries about the robot. Each query has a start cell, a finish cell and a value $$$k$$$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times?The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.
Input Specification: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of rows and columns of the grid. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$0 \le a_i \le n$$$) — the number of blocked cells on the bottom of the $$$i$$$-th column. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contain five integers $$$x_s, y_s, x_f, y_f$$$ and $$$k$$$ ($$$a[y_s] < x_s \le n$$$; $$$1 \le y_s \le m$$$; $$$a[y_f] < x_f \le n$$$; $$$1 \le y_f \le m$$$; $$$1 \le k \le 10^9$$$) — the row and the column of the start cell, the row and the column of the finish cell and the number of times each your command is executed. The start and the finish cell of each query are unblocked.
Output Specification: For each query, print "YES" if you can send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times. Otherwise, print "NO".
Code:
import math
import sys
input = sys.stdin.buffer.readline
y, x_ = input().split()
block = [int(x) for x in input().split()]
list2 = [[0] *20 for i in range( len(block))]
for a in range(len(block)):
list2[a][0] = block[a]
z, x = 0, 1
while (1 << x) <= len(block):
z = 0
while (z + (1 << x) - 1) < len(block):
list2[z][x] = (max(list2[z][x - 1], list2[z + (1 << (x - 1))][x - 1]))
z += 1
x += 1
for i in range(int(input())):
s = [int(x) for x in input().split()]
if abs(s[0] - s[2]) % s[-1] != 0 or abs(s[1] - s[3]) % s[-1] != 0:
print("NO")
else:
smaller = min(s[1], s[3])
bigger = max(s[1], s[3])
k = 0
while (1 << (k + 1)) <= bigger - smaller + 1:
k += 1
highest = max(list2[smaller - 1][k], list2[bigger - (1 << k)][k])
if highest < s[-1] * ((int(y) - s[0]) // s[-1]) + s[0]:
print("YES")
else:
# TODO: Your code here
|
import math
import sys
input = sys.stdin.buffer.readline
y, x_ = input().split()
block = [int(x) for x in input().split()]
list2 = [[0] *20 for i in range( len(block))]
for a in range(len(block)):
list2[a][0] = block[a]
z, x = 0, 1
while (1 << x) <= len(block):
z = 0
while (z + (1 << x) - 1) < len(block):
list2[z][x] = (max(list2[z][x - 1], list2[z + (1 << (x - 1))][x - 1]))
z += 1
x += 1
for i in range(int(input())):
s = [int(x) for x in input().split()]
if abs(s[0] - s[2]) % s[-1] != 0 or abs(s[1] - s[3]) % s[-1] != 0:
print("NO")
else:
smaller = min(s[1], s[3])
bigger = max(s[1], s[3])
k = 0
while (1 << (k + 1)) <= bigger - smaller + 1:
k += 1
highest = max(list2[smaller - 1][k], list2[bigger - (1 << k)][k])
if highest < s[-1] * ((int(y) - s[0]) // s[-1]) + s[0]:
print("YES")
else:
{{completion}}
|
print("NO")
|
[{"input": "11 10\n9 0 0 10 3 4 8 11 10 8\n6\n1 2 1 3 1\n1 2 1 3 2\n4 3 4 5 2\n5 3 11 5 3\n5 3 11 5 2\n11 9 9 10 1", "output": ["YES\nNO\nNO\nNO\nYES\nYES"]}]
|
block_completion_002991
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a_1, a_2, \dots, a_n$$$, which is sorted in non-descending order. You decided to perform the following steps to create array $$$b_1, b_2, \dots, b_n$$$: Create an array $$$d$$$ consisting of $$$n$$$ arbitrary non-negative integers. Set $$$b_i = a_i + d_i$$$ for each $$$b_i$$$. Sort the array $$$b$$$ in non-descending order. You are given the resulting array $$$b$$$. For each index $$$i$$$, calculate what is the minimum and maximum possible value of $$$d_i$$$ you can choose in order to get the given array $$$b$$$.Note that the minimum (maximum) $$$d_i$$$-s are independent of each other, i. e. they can be obtained from different possible arrays $$$d$$$.
Input Specification: The first line contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of arrays $$$a$$$, $$$b$$$ and $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_i \le a_{i+1}$$$) — the array $$$a$$$ in non-descending order. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$) — the array $$$b$$$ in non-descending order. Additional constraints on the input: there is at least one way to obtain the array $$$b$$$ from the $$$a$$$ by choosing an array $$$d$$$ consisting of non-negative integers; the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case, print two lines. In the first line, print $$$n$$$ integers $$$d_1^{min}, d_2^{min}, \dots, d_n^{min}$$$, where $$$d_i^{min}$$$ is the minimum possible value you can add to $$$a_i$$$. Secondly, print $$$n$$$ integers $$$d_1^{max}, d_2^{max}, \dots, d_n^{max}$$$, where $$$d_i^{max}$$$ is the maximum possible value you can add to $$$a_i$$$. All $$$d_i^{min}$$$ and $$$d_i^{max}$$$ values are independent of each other. In other words, for each $$$i$$$, $$$d_i^{min}$$$ is just the minimum value among all possible values of $$$d_i$$$.
Notes: NoteIn the first test case, in order to get $$$d_1^{min} = 5$$$, we can choose, for example, $$$d = [5, 10, 6]$$$. Then $$$b$$$ $$$=$$$ $$$[2+5,3+10,5+6]$$$ $$$=$$$ $$$[7,13,11]$$$ $$$=$$$ $$$[7,11,13]$$$.For $$$d_2^{min} = 4$$$, we can choose $$$d$$$ $$$=$$$ $$$[9, 4, 8]$$$. Then $$$b$$$ $$$=$$$ $$$[2+9,3+4,5+8]$$$ $$$=$$$ $$$[11,7,13]$$$ $$$=$$$ $$$[7,11,13]$$$.
Code:
import sys
from math import ceil
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
ls.append(lst)
for l in ls:
sys.stderr.write(l + ('\n'))
sys.stderr.write("-- output --\n")
def at_least(L, x):
for i in range(len(L)):
if L[i] >= x:
return i
return len(L)-1
def at_most(L, x):
for i in range(len(L)-1, -1, -1):
if L[i] <= x:
return i
return 0
def solve(n, a, b):
dmin, dmax = [-1]*n, [-1]*n
imin, imax = 0, n-1
for i in range(n):
while b[imin] < a[i]:
imin += 1
dmin[i] = b[imin] - a[i]
dmax[n-1-i] = b[imax] - a[n-1-i]
if i < n-1:
if # TODO: Your code here:
imax = n-i-2
return dmin, dmax
for i in range(1, len(ls)-1, 3):
n = int(ls[i])
a = [int(x) for x in ls[i+1].split(' ')]
b = [int(x) for x in ls[i+2].split(' ')]
dmin, dmax = solve(n, a, b)
print(*dmin)
print(*dmax)
|
import sys
from math import ceil
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
ls.append(lst)
for l in ls:
sys.stderr.write(l + ('\n'))
sys.stderr.write("-- output --\n")
def at_least(L, x):
for i in range(len(L)):
if L[i] >= x:
return i
return len(L)-1
def at_most(L, x):
for i in range(len(L)-1, -1, -1):
if L[i] <= x:
return i
return 0
def solve(n, a, b):
dmin, dmax = [-1]*n, [-1]*n
imin, imax = 0, n-1
for i in range(n):
while b[imin] < a[i]:
imin += 1
dmin[i] = b[imin] - a[i]
dmax[n-1-i] = b[imax] - a[n-1-i]
if i < n-1:
if {{completion}}:
imax = n-i-2
return dmin, dmax
for i in range(1, len(ls)-1, 3):
n = int(ls[i])
a = [int(x) for x in ls[i+1].split(' ')]
b = [int(x) for x in ls[i+2].split(' ')]
dmin, dmax = solve(n, a, b)
print(*dmin)
print(*dmax)
|
b[n-i-2] < a[n-i-1]
|
[{"input": "4\n\n3\n\n2 3 5\n\n7 11 13\n\n1\n\n1000\n\n5000\n\n4\n\n1 2 3 4\n\n1 2 3 4\n\n4\n\n10 20 30 40\n\n22 33 33 55", "output": ["5 4 2\n11 10 8\n4000\n4000\n0 0 0 0\n0 0 0 0\n12 2 3 15\n23 13 3 15"]}]
|
control_completion_002703
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Julia's $$$n$$$ friends want to organize a startup in a new country they moved to. They assigned each other numbers from 1 to $$$n$$$ according to the jobs they have, from the most front-end tasks to the most back-end ones. They also estimated a matrix $$$c$$$, where $$$c_{ij} = c_{ji}$$$ is the average number of messages per month between people doing jobs $$$i$$$ and $$$j$$$.Now they want to make a hierarchy tree. It will be a binary tree with each node containing one member of the team. Some member will be selected as a leader of the team and will be contained in the root node. In order for the leader to be able to easily reach any subordinate, for each node $$$v$$$ of the tree, the following should apply: all members in its left subtree must have smaller numbers than $$$v$$$, and all members in its right subtree must have larger numbers than $$$v$$$.After the hierarchy tree is settled, people doing jobs $$$i$$$ and $$$j$$$ will be communicating via the shortest path in the tree between their nodes. Let's denote the length of this path as $$$d_{ij}$$$. Thus, the cost of their communication is $$$c_{ij} \cdot d_{ij}$$$.Your task is to find a hierarchy tree that minimizes the total cost of communication over all pairs: $$$\sum_{1 \le i < j \le n} c_{ij} \cdot d_{ij}$$$.
Input Specification: The first line contains an integer $$$n$$$ ($$$1 \le n \le 200$$$) – the number of team members organizing a startup. The next $$$n$$$ lines contain $$$n$$$ integers each, $$$j$$$-th number in $$$i$$$-th line is $$$c_{ij}$$$ — the estimated number of messages per month between team members $$$i$$$ and $$$j$$$ ($$$0 \le c_{ij} \le 10^9; c_{ij} = c_{ji}; c_{ii} = 0$$$).
Output Specification: Output a description of a hierarchy tree that minimizes the total cost of communication. To do so, for each team member from 1 to $$$n$$$ output the number of the member in its parent node, or 0 for the leader. If there are many optimal trees, output a description of any one of them.
Notes: NoteThe minimal possible total cost is $$$566 \cdot 1+239 \cdot 1+30 \cdot 1+1 \cdot 2+1 \cdot 2=839$$$:
Code:
n = int(input().strip())
S = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j, c in enumerate(map(int, input().strip().split())):
S[i][j] = c
for i in range(n):
for j in range(n):
if i > 0 and j > 0:
S[i][j] += S[i][j-1] + S[i-1][j] - S[i-1][j-1]
elif i > 0:
S[i][j] += S[i-1][j]
elif j > 0:
# TODO: Your code here
def acc(i1, i2, j1, j2):
if i1 >= i2 or j1 >= j2:
return 0
a = S[i2-1][j2-1]
b = S[i2-1][j1-1] if j1 > 0 else 0
c = S[i1-1][j2-1] if i1 > 0 else 0
d = S[i1-1][j1-1] if i1 > 0 and j1 > 0 else 0
return a - b - c + d
M = [[-1 for i in range(n)] for j in range(n)]
P = [[-1 for i in range(n)] for j in range(n)]
def solve(b, e):
if e - b == 1:
M[b][e-1] = 0
return 0
if e - b == 0:
return 0
if M[b][e-1] != -1:
return M[b][e-1]
M[b][e-1] = 1e18
for i in range(b, e):
s = solve(b, i) + solve(i+1, e)
s += acc(0, b, b, i) + acc(b, i, i, n) + acc(0, i+1, i+1, e) + acc(i+1, e, e, n)
if s < M[b][e-1]:
M[b][e-1] = s
P[b][e-1] = i
return M[b][e-1]
solve(0, n)
sol = ["" for _ in range(n)]
def label(b, e, p):
if e - b == 1:
sol[b] = str(p)
return
elif e - b == 0:
return
i = P[b][e-1]
sol[i] = str(p)
label(b, i, i+1)
label(i+1, e, i+1)
label(0, n, 0)
print(" ".join(sol))
|
n = int(input().strip())
S = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j, c in enumerate(map(int, input().strip().split())):
S[i][j] = c
for i in range(n):
for j in range(n):
if i > 0 and j > 0:
S[i][j] += S[i][j-1] + S[i-1][j] - S[i-1][j-1]
elif i > 0:
S[i][j] += S[i-1][j]
elif j > 0:
{{completion}}
def acc(i1, i2, j1, j2):
if i1 >= i2 or j1 >= j2:
return 0
a = S[i2-1][j2-1]
b = S[i2-1][j1-1] if j1 > 0 else 0
c = S[i1-1][j2-1] if i1 > 0 else 0
d = S[i1-1][j1-1] if i1 > 0 and j1 > 0 else 0
return a - b - c + d
M = [[-1 for i in range(n)] for j in range(n)]
P = [[-1 for i in range(n)] for j in range(n)]
def solve(b, e):
if e - b == 1:
M[b][e-1] = 0
return 0
if e - b == 0:
return 0
if M[b][e-1] != -1:
return M[b][e-1]
M[b][e-1] = 1e18
for i in range(b, e):
s = solve(b, i) + solve(i+1, e)
s += acc(0, b, b, i) + acc(b, i, i, n) + acc(0, i+1, i+1, e) + acc(i+1, e, e, n)
if s < M[b][e-1]:
M[b][e-1] = s
P[b][e-1] = i
return M[b][e-1]
solve(0, n)
sol = ["" for _ in range(n)]
def label(b, e, p):
if e - b == 1:
sol[b] = str(p)
return
elif e - b == 0:
return
i = P[b][e-1]
sol[i] = str(p)
label(b, i, i+1)
label(i+1, e, i+1)
label(0, n, 0)
print(" ".join(sol))
|
S[i][j] += S[i][j-1]
|
[{"input": "4\n0 566 1 0\n566 0 239 30\n1 239 0 1\n0 30 1 0", "output": ["2 4 2 0"]}]
|
block_completion_003209
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $$$v$$$ (different from root) is the previous to $$$v$$$ vertex on the shortest path from the root to the vertex $$$v$$$. Children of the vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent.You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex $$$v$$$, if at least one child of $$$v$$$ is infected, you can spread the disease by infecting at most one other child of $$$v$$$ of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of the vertices in the given tree. The second line of each test case contains $$$n - 1$$$ integers $$$p_2, p_3, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ is the ancestor of the $$$i$$$-th vertex in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case you should output a single integer — the minimal number of seconds needed to infect the whole tree.
Notes: NoteThe image depicts the tree from the first test case during each second.A vertex is black if it is not infected. A vertex is blue if it is infected by injection during the previous second. A vertex is green if it is infected by spreading during the previous second. A vertex is red if it is infected earlier than the previous second. Note that you are able to choose which vertices are infected by spreading and by injections.
Code:
from collections import defaultdict
counter = defaultdict(int)
def solve(a):
for ai in a:
counter[ai] += 1
count = list(counter.values())
num_level = len(count)
count.sort()
for i in range(num_level):
count[i] = max(count[i] - i - 2, 0)
L = 0; R = max(count)
if R == 0:
return num_level + 1
def check(k):
b = count.copy()
for i in range(len(b)):
b[i] = max(b[i] - k, 0)
if # TODO: Your code here:
return True
return False
while R - L > 1:
mid = (R + L) // 2
if(check(mid)):
R = mid
else:
L = mid
return num_level + 1 + R
for a in [*open(0)][2::2]:
counter.clear()
res = solve(a.split())
print(res)
|
from collections import defaultdict
counter = defaultdict(int)
def solve(a):
for ai in a:
counter[ai] += 1
count = list(counter.values())
num_level = len(count)
count.sort()
for i in range(num_level):
count[i] = max(count[i] - i - 2, 0)
L = 0; R = max(count)
if R == 0:
return num_level + 1
def check(k):
b = count.copy()
for i in range(len(b)):
b[i] = max(b[i] - k, 0)
if {{completion}}:
return True
return False
while R - L > 1:
mid = (R + L) // 2
if(check(mid)):
R = mid
else:
L = mid
return num_level + 1 + R
for a in [*open(0)][2::2]:
counter.clear()
res = solve(a.split())
print(res)
|
sum(b) <= k
|
[{"input": "5\n7\n1 1 1 2 2 4\n5\n5 5 1 4\n2\n1\n3\n3 1\n6\n1 1 1 1 1", "output": ["4\n4\n2\n3\n4"]}]
|
control_completion_004317
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Inflation has occurred in Berlandia, so the store needs to change the price of goods.The current price of good $$$n$$$ is given. It is allowed to increase the price of the good by $$$k$$$ times, with $$$1 \le k \le m$$$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.For example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).If there are several possible variants, output the one in which the new price is maximal.If it is impossible to get a rounder price, output $$$n \cdot m$$$ (that is, the maximum possible price).
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Each test case consists of one line. This line contains two integers: $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$). Where $$$n$$$ is the old price of the good, and the number $$$m$$$ means that you can increase the price $$$n$$$ no more than $$$m$$$ times.
Output Specification: For each test case, output on a separate line the roundest integer of the form $$$n \cdot k$$$ ($$$1 \le k \le m$$$, $$$k$$$ — an integer). If there are several possible variants, output the one in which the new price (value $$$n \cdot k$$$) is maximal. If it is impossible to get a more rounded price, output $$$n \cdot m$$$ (that is, the maximum possible price).
Notes: NoteIn the first case $$$n = 6$$$, $$$m = 11$$$. We cannot get a number with two zeros or more at the end, because we need to increase the price $$$50$$$ times, but $$$50 > m = 11$$$. The maximum price multiple of $$$10$$$ would be $$$6 \cdot 10 = 60$$$.In the second case $$$n = 5$$$, $$$m = 43$$$. The maximum price multiple of $$$100$$$ would be $$$5 \cdot 40 = 200$$$.In the third case, $$$n = 13$$$, $$$m = 5$$$. All possible new prices will not end in $$$0$$$, then you should output $$$n \cdot m = 65$$$.In the fourth case, you should increase the price $$$15$$$ times.In the fifth case, increase the price $$$12000$$$ times.
Code:
from sys import stdin, stderr
data = [int(x) for x in stdin.read().split()[1:]]
ns, ms = data[::2], data[1::2]
output = []
for n, m in zip(ns, ms):
# n = 2 ** a * 5 ** b * c
a = b = 0
c = n
while c % 2 == 0:
a += 1
c //= 2
while c % 5 == 0:
b += 1
c //= 5
t = 1 # our result should be a multiple of t
if a > b:
while a > b and 5 * t <= m:
t *= 5
b += 1
elif b > a:
while b > a and 2 * t <= m:
# TODO: Your code here
while 10 * t <= m:
t *= 10
#print(n, m, t, file=stderr)
output.append(n * (m - (m % t)))
print('\n'.join(str(x) for x in output))
|
from sys import stdin, stderr
data = [int(x) for x in stdin.read().split()[1:]]
ns, ms = data[::2], data[1::2]
output = []
for n, m in zip(ns, ms):
# n = 2 ** a * 5 ** b * c
a = b = 0
c = n
while c % 2 == 0:
a += 1
c //= 2
while c % 5 == 0:
b += 1
c //= 5
t = 1 # our result should be a multiple of t
if a > b:
while a > b and 5 * t <= m:
t *= 5
b += 1
elif b > a:
while b > a and 2 * t <= m:
{{completion}}
while 10 * t <= m:
t *= 10
#print(n, m, t, file=stderr)
output.append(n * (m - (m % t)))
print('\n'.join(str(x) for x in output))
|
t *= 2
a += 1
|
[{"input": "10\n\n6 11\n\n5 43\n\n13 5\n\n4 16\n\n10050 12345\n\n2 6\n\n4 30\n\n25 10\n\n2 81\n\n1 7", "output": ["60\n200\n65\n60\n120600000\n10\n100\n200\n100\n7"]}]
|
block_completion_001335
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer — the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for s in[*open(0)][2::2]:# TODO: Your code here
|
for s in[*open(0)][2::2]:{{completion}}
|
a,b,*_,c,d=sorted(map(int,s.split()));print(c+d-a-b)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005385
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given $$$n$$$ points on the plane, the coordinates of the $$$i$$$-th point are $$$(x_i, y_i)$$$. No two points have the same coordinates.The distance between points $$$i$$$ and $$$j$$$ is defined as $$$d(i,j) = |x_i - x_j| + |y_i - y_j|$$$.For each point, you have to choose a color, represented by an integer from $$$1$$$ to $$$n$$$. For every ordered triple of different points $$$(a,b,c)$$$, the following constraints should be met: if $$$a$$$, $$$b$$$ and $$$c$$$ have the same color, then $$$d(a,b) = d(a,c) = d(b,c)$$$; if $$$a$$$ and $$$b$$$ have the same color, and the color of $$$c$$$ is different from the color of $$$a$$$, then $$$d(a,b) < d(a,c)$$$ and $$$d(a,b) < d(b,c)$$$. Calculate the number of different ways to choose the colors that meet these constraints.
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of points. Then $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^8$$$). No two points have the same coordinates (i. e. if $$$i \ne j$$$, then either $$$x_i \ne x_j$$$ or $$$y_i \ne y_j$$$).
Output Specification: Print one integer — the number of ways to choose the colors for the points. Since it can be large, print it modulo $$$998244353$$$.
Notes: NoteIn the first test, the following ways to choose the colors are suitable: $$$[1, 1, 1]$$$; $$$[2, 2, 2]$$$; $$$[3, 3, 3]$$$; $$$[1, 2, 3]$$$; $$$[1, 3, 2]$$$; $$$[2, 1, 3]$$$; $$$[2, 3, 1]$$$; $$$[3, 1, 2]$$$; $$$[3, 2, 1]$$$.
Code:
from math import perm, comb
import sys
input = sys.stdin.readline
M = 998244353
n = int(input())
x, y = [0]*n, [0]*n
for i in range(n):
x[i], y[i] = map(int, input().split())
# print(x, y)
dist = [[] for _ in range(n)]
for i in range(n):
for j in range(n):
dist[i].append(abs(x[i] - x[j]) + abs(y[i] - y[j]))
# print(dist)
mindist, nbr = [M] * n, [[] for _ in range(n)]
for i in range(n):
for j in range(n):
if i == j:
continue
if dist[i][j] < mindist[i]:
mindist[i] = dist[i][j]
nbr[i] = [j]
elif dist[i][j] == mindist[i]:
# TODO: Your code here
# print(mindist, nbr)
grp = [0] * n
for i in range(n):
if grp[i] > 0:
continue
if len(nbr[i]) > 3:
grp[i] = 1
continue
checknbr = [False] * n
checknbr[i] = True
for j in nbr[i]:
checknbr[j] = True
check = False
for j in nbr[i]:
if len(nbr[j]) != len(nbr[i]):
check = True
break
for c in nbr[j]:
if not checknbr[c]:
check = True
break
if check:
grp[i] = 1
else:
grp[i] = len(nbr[i]) + 1
for j in nbr[i]:
grp[j] = grp[i]
# print(grp)
cnt = [0] * 5
for i in grp:
cnt[i] += 1
cnt[2] //= 2
cnt[3] //= 3
cnt[4] //= 4
# print(cnt)
ans = 0
for i in range(cnt[2] + 1):
for j in range(cnt[3] + 1):
for k in range(cnt[4] + 1):
z = (comb(cnt[2], i) * comb(cnt[3], j) * comb(cnt[4], k)) % M
z *= perm(n, n - i - 2*j - 3*k)
z %= M
ans = (ans + z) % M
print(ans)
|
from math import perm, comb
import sys
input = sys.stdin.readline
M = 998244353
n = int(input())
x, y = [0]*n, [0]*n
for i in range(n):
x[i], y[i] = map(int, input().split())
# print(x, y)
dist = [[] for _ in range(n)]
for i in range(n):
for j in range(n):
dist[i].append(abs(x[i] - x[j]) + abs(y[i] - y[j]))
# print(dist)
mindist, nbr = [M] * n, [[] for _ in range(n)]
for i in range(n):
for j in range(n):
if i == j:
continue
if dist[i][j] < mindist[i]:
mindist[i] = dist[i][j]
nbr[i] = [j]
elif dist[i][j] == mindist[i]:
{{completion}}
# print(mindist, nbr)
grp = [0] * n
for i in range(n):
if grp[i] > 0:
continue
if len(nbr[i]) > 3:
grp[i] = 1
continue
checknbr = [False] * n
checknbr[i] = True
for j in nbr[i]:
checknbr[j] = True
check = False
for j in nbr[i]:
if len(nbr[j]) != len(nbr[i]):
check = True
break
for c in nbr[j]:
if not checknbr[c]:
check = True
break
if check:
grp[i] = 1
else:
grp[i] = len(nbr[i]) + 1
for j in nbr[i]:
grp[j] = grp[i]
# print(grp)
cnt = [0] * 5
for i in grp:
cnt[i] += 1
cnt[2] //= 2
cnt[3] //= 3
cnt[4] //= 4
# print(cnt)
ans = 0
for i in range(cnt[2] + 1):
for j in range(cnt[3] + 1):
for k in range(cnt[4] + 1):
z = (comb(cnt[2], i) * comb(cnt[3], j) * comb(cnt[4], k)) % M
z *= perm(n, n - i - 2*j - 3*k)
z %= M
ans = (ans + z) % M
print(ans)
|
nbr[i].append(j)
|
[{"input": "3\n1 0\n3 0\n2 1", "output": ["9"]}, {"input": "5\n1 2\n2 4\n3 4\n4 4\n1 3", "output": ["240"]}, {"input": "4\n1 0\n3 0\n2 1\n2 0", "output": ["24"]}]
|
block_completion_000544
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
t=int(input())
for i in range(t):
n=int(input())
result=0
dic1={}
dic2={}
dic3={}
for i in range(n):
S=input()
if # TODO: Your code here:
result+=dic1[S[0]]
dic1[S[0]]+=1
else:
dic1[S[0]]=1
if S[1] in dic2:
result+=dic2[S[1]]
dic2[S[1]]+=1
else:
dic2[S[1]]=1
if S in dic3:
result-=dic3[S]*2
dic3[S]+=1
else:
dic3[S]=1
print(result)
|
t=int(input())
for i in range(t):
n=int(input())
result=0
dic1={}
dic2={}
dic3={}
for i in range(n):
S=input()
if {{completion}}:
result+=dic1[S[0]]
dic1[S[0]]+=1
else:
dic1[S[0]]=1
if S[1] in dic2:
result+=dic2[S[1]]
dic2[S[1]]+=1
else:
dic2[S[1]]=1
if S in dic3:
result-=dic3[S]*2
dic3[S]+=1
else:
dic3[S]=1
print(result)
|
S[0] in dic1
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
control_completion_000872
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Notes: NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.
Code:
from collections import Counter
from itertools import islice
from sys import stdin
LETTERS = 'abcdefghijk'
data = (line.strip() for line in stdin.readlines()[1:])
res = []
for line in data:
n = int(line)
s = 0
ctr = Counter()
for ab in islice(data, n):
a, b = ab
ctr[ab] += 1
for l in LETTERS:
if # TODO: Your code here:
s += ctr[f'{l}{b}']
if l != b:
s += ctr[f'{a}{l}']
res.append(s)
print('\n'.join(str(x) for x in res))
|
from collections import Counter
from itertools import islice
from sys import stdin
LETTERS = 'abcdefghijk'
data = (line.strip() for line in stdin.readlines()[1:])
res = []
for line in data:
n = int(line)
s = 0
ctr = Counter()
for ab in islice(data, n):
a, b = ab
ctr[ab] += 1
for l in LETTERS:
if {{completion}}:
s += ctr[f'{l}{b}']
if l != b:
s += ctr[f'{a}{l}']
res.append(s)
print('\n'.join(str(x) for x in res))
|
l != a
|
[{"input": "4\n6\nab\ncb\ndb\naa\ncc\nef\n7\naa\nbb\ncc\nac\nca\nbb\naa\n4\nkk\nkk\nab\nab\n5\njf\njf\njk\njk\njk", "output": ["5\n6\n0\n6"]}]
|
control_completion_000865
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can: Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.
Input Specification: The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).
Output Specification: For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.
Notes: NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$. During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$; during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.
Code:
from bisect import bisect
t = int(input().strip())
def solve(o, t):
if t - o > 1:
d = (t - o) // 3 + ((t - o) % 3 == 2)
o, t = o + 2 * d, t - d
return (o + (t > o)) * 2 - (o > t)
out = []
for _ in range(t):
n = int(input().strip())
h = list(map(int, input().strip().split()))
mx = max(h)
o, t, e = 0, 0, 0
for # TODO: Your code here:
e += (mx - x + 1) % 2
o += (mx - x) % 2
t += (mx - x) // 2
out.append(str(min(solve(o, t), solve(e, t + o))))
print("\n".join(out))
|
from bisect import bisect
t = int(input().strip())
def solve(o, t):
if t - o > 1:
d = (t - o) // 3 + ((t - o) % 3 == 2)
o, t = o + 2 * d, t - d
return (o + (t > o)) * 2 - (o > t)
out = []
for _ in range(t):
n = int(input().strip())
h = list(map(int, input().strip().split()))
mx = max(h)
o, t, e = 0, 0, 0
for {{completion}}:
e += (mx - x + 1) % 2
o += (mx - x) % 2
t += (mx - x) // 2
out.append(str(min(solve(o, t), solve(e, t + o))))
print("\n".join(out))
|
x in h
|
[{"input": "3\n3\n1 2 4\n5\n4 4 3 5 5\n7\n2 5 4 8 3 7 4", "output": ["4\n3\n16"]}]
|
control_completion_003362
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
Input Specification: The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
Output Specification: You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
Notes: NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12>11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
Code:
input = __import__('sys').stdin.readline
class DisjointSetUnion(object):
def __init__(self, n):
self.n = n
self.par = [i for i in range(n)]
def find(self, x):
toupdate = []
while x != self.par[x]:
# TODO: Your code here
for u in toupdate:
self.par[u] = x
return x
def merge(self, u, v):
u = self.find(u)
v = self.find(v)
if u != v:
self.par[u] = v
return u != v
n, m = map(int, input().split())
dsu = DisjointSetUnion(n)
adj = [[] for _ in range(n)] # adjlist of the MST
outOfTrees = [] # outside the MST
for _ in range(m):
u, v = map(lambda x: int(x)-1, input().split())
if dsu.merge(u, v):
adj[u].append(v)
adj[v].append(u)
else:
outOfTrees.append((u, v))
# print('outOfTrees', outOfTrees)
# init lca
jump = [[0] * n]
depth = [0] * n
stack = [(0, -1)] # (u, par)
while len(stack) > 0:
u, par = stack.pop()
jump[0][u] = par
for v in adj[u]:
if v != par:
depth[v] = depth[u] + 1
stack.append((v, u))
for j in range(20):
jump.append([jump[-1][jump[-1][u]] for u in range(n)])
def moveTo(u, step):
for i in range(20):
if (step >> i) & 1 == 1:
u = jump[i][u]
return u
def lca(u, v):
if depth[u] < depth[v]:
u, v = v, u
u = moveTo(u, depth[u] - depth[v])
if u == v:
return u
for i in range(19, -1, -1):
if jump[i][u] != jump[i][v]:
u, v = jump[i][u], jump[i][v]
return jump[0][u]
# check each edges out of the tree
psum = [0] * n
for u, v in outOfTrees:
# nodes in the path (and its subtrees) u to v (not including u & v) will select edge u-v in their dfs process
r = lca(u, v)
# print('lca', u+1, v+1, r+1)
if r == u:
psum[moveTo(v, depth[v] - depth[u] - 1)] += 1
psum[v] -= 1
elif r == v:
psum[moveTo(u, depth[u] - depth[v] - 1)] += 1
psum[u] -= 1
else:
psum[0] += 1
psum[u] -= 1
psum[v] -= 1
# print('psum_initial', psum)
# print('applyToChild', applyToChild)
stack = [(0, -1)] # (u, par)
while len(stack) > 0:
u, par = stack.pop()
for v in adj[u]:
if v != par:
psum[v] += psum[u]
stack.append((v, u))
# print('psum', psum)
print(''.join('1' if psum[u] == 0 else '0' for u in range(n)))
|
input = __import__('sys').stdin.readline
class DisjointSetUnion(object):
def __init__(self, n):
self.n = n
self.par = [i for i in range(n)]
def find(self, x):
toupdate = []
while x != self.par[x]:
{{completion}}
for u in toupdate:
self.par[u] = x
return x
def merge(self, u, v):
u = self.find(u)
v = self.find(v)
if u != v:
self.par[u] = v
return u != v
n, m = map(int, input().split())
dsu = DisjointSetUnion(n)
adj = [[] for _ in range(n)] # adjlist of the MST
outOfTrees = [] # outside the MST
for _ in range(m):
u, v = map(lambda x: int(x)-1, input().split())
if dsu.merge(u, v):
adj[u].append(v)
adj[v].append(u)
else:
outOfTrees.append((u, v))
# print('outOfTrees', outOfTrees)
# init lca
jump = [[0] * n]
depth = [0] * n
stack = [(0, -1)] # (u, par)
while len(stack) > 0:
u, par = stack.pop()
jump[0][u] = par
for v in adj[u]:
if v != par:
depth[v] = depth[u] + 1
stack.append((v, u))
for j in range(20):
jump.append([jump[-1][jump[-1][u]] for u in range(n)])
def moveTo(u, step):
for i in range(20):
if (step >> i) & 1 == 1:
u = jump[i][u]
return u
def lca(u, v):
if depth[u] < depth[v]:
u, v = v, u
u = moveTo(u, depth[u] - depth[v])
if u == v:
return u
for i in range(19, -1, -1):
if jump[i][u] != jump[i][v]:
u, v = jump[i][u], jump[i][v]
return jump[0][u]
# check each edges out of the tree
psum = [0] * n
for u, v in outOfTrees:
# nodes in the path (and its subtrees) u to v (not including u & v) will select edge u-v in their dfs process
r = lca(u, v)
# print('lca', u+1, v+1, r+1)
if r == u:
psum[moveTo(v, depth[v] - depth[u] - 1)] += 1
psum[v] -= 1
elif r == v:
psum[moveTo(u, depth[u] - depth[v] - 1)] += 1
psum[u] -= 1
else:
psum[0] += 1
psum[u] -= 1
psum[v] -= 1
# print('psum_initial', psum)
# print('applyToChild', applyToChild)
stack = [(0, -1)] # (u, par)
while len(stack) > 0:
u, par = stack.pop()
for v in adj[u]:
if v != par:
psum[v] += psum[u]
stack.append((v, u))
# print('psum', psum)
print(''.join('1' if psum[u] == 0 else '0' for u in range(n)))
|
toupdate.append(x)
x = self.par[x]
|
[{"input": "5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "output": ["01111"]}, {"input": "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6", "output": ["0011111011"]}]
|
block_completion_006772
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following: For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.
Output Specification: For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.
Notes: NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.
Code:
input = __import__('sys').stdin.readline
def solve():
n, m = map(int, input().split())
mx = (0, -1)
mn = (10**18, -1)
for i in range(n):
current, total = 0, 0
for x in map(int, input().split()):
# TODO: Your code here
mx = max(mx, (total, i))
mn = min(mn, (total, i))
print(mn[1]+1, mx[0] - mn[0])
for _ in range(int(input())):
solve()
|
input = __import__('sys').stdin.readline
def solve():
n, m = map(int, input().split())
mx = (0, -1)
mn = (10**18, -1)
for i in range(n):
current, total = 0, 0
for x in map(int, input().split()):
{{completion}}
mx = max(mx, (total, i))
mn = min(mn, (total, i))
print(mn[1]+1, mx[0] - mn[0])
for _ in range(int(input())):
solve()
|
current += x
total += current
|
[{"input": "7\n3 9\n0 1 2 0 0 2 1 1 0\n0 1 1 1 2 0 0 2 0\n0 1 2 0 0 1 2 1 0\n3 7\n25 15 20 15 25 20 20\n26 14 20 14 26 20 20\n25 15 20 15 20 20 25\n3 9\n25 15 20 15 25 20 20 20 20\n26 14 20 14 26 20 20 20 20\n25 15 20 15 25 15 20 20 25\n3 11\n25 15 20 15 25 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20\n25 15 20 15 25 20 15 20 20 20 25\n3 13\n25 15 20 15 25 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 15 20 20 20 20 25\n3 15\n25 15 20 15 25 20 20 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 20 15 20 20 20 20 20 25\n3 9\n909459 479492 676924 224197 162866 164495 193268 742456 728277\n948845 455424 731850 327890 304150 237351 251763 225845 798316\n975446 401170 792914 272263 300770 242037 236619 334316 725899", "output": ["3 1\n3 10\n3 15\n3 20\n3 25\n3 30\n1 1378716"]}]
|
block_completion_002631
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array $$$[1, 1, 1]$$$ is $$$1$$$; $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$; $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.
Input Specification: In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).
Output Specification: Print the answer to each query on a new line.
Notes: NoteAfter the first query $$$a$$$ is equal to $$$[1, 2, 2, 4, 5]$$$, and the answer is $$$29$$$ because we can split each of the subsegments the following way: $$$[1; 1]$$$: $$$[1]$$$, 1 block; $$$[1; 2]$$$: $$$[1] + [2]$$$, 2 blocks; $$$[1; 3]$$$: $$$[1] + [2, 2]$$$, 2 blocks; $$$[1; 4]$$$: $$$[1] + [2, 2] + [4]$$$, 3 blocks; $$$[1; 5]$$$: $$$[1] + [2, 2] + [4] + [5]$$$, 4 blocks; $$$[2; 2]$$$: $$$[2]$$$, 1 block; $$$[2; 3]$$$: $$$[2, 2]$$$, 1 block; $$$[2; 4]$$$: $$$[2, 2] + [4]$$$, 2 blocks; $$$[2; 5]$$$: $$$[2, 2] + [4] + [5]$$$, 3 blocks; $$$[3; 3]$$$: $$$[2]$$$, 1 block; $$$[3; 4]$$$: $$$[2] + [4]$$$, 2 blocks; $$$[3; 5]$$$: $$$[2] + [4] + [5]$$$, 3 blocks; $$$[4; 4]$$$: $$$[4]$$$, 1 block; $$$[4; 5]$$$: $$$[4] + [5]$$$, 2 blocks; $$$[5; 5]$$$: $$$[5]$$$, 1 block; which is $$$1 + 2 + 2 + 3 + 4 + 1 + 1 + 2 + 3 + 1 + 2 + 3 + 1 + 2 + 1 = 29$$$ in total.
Code:
import time, sys
n, m = [int(i) for i in sys.stdin.readline().split()]
a = [int(i) for i in sys.stdin.readline().split()]
t1 = time.time()
w = [(i+1)*(n-i-1) for i in range(n-1)]
c = sum([w[i] if a[i+1] != a[i] else 0 for i in range(n-1)])
for _ in range(m):
ix, x = [int(i) for i in sys.stdin.readline().split()]
ix -= 1
if ix != 0:
if a[ix] == a[ix-1] != x:
c += w[ix-1]
elif a[ix] != a[ix-1] == x:
c -= w[ix-1]
if ix != n-1:
if a[ix] == a[ix+1] != x:
c += w[ix]
elif # TODO: Your code here:
c -= w[ix]
a[ix] = x
sys.stdout.write(str(c+(n*(n+1))//2) + '\n')
|
import time, sys
n, m = [int(i) for i in sys.stdin.readline().split()]
a = [int(i) for i in sys.stdin.readline().split()]
t1 = time.time()
w = [(i+1)*(n-i-1) for i in range(n-1)]
c = sum([w[i] if a[i+1] != a[i] else 0 for i in range(n-1)])
for _ in range(m):
ix, x = [int(i) for i in sys.stdin.readline().split()]
ix -= 1
if ix != 0:
if a[ix] == a[ix-1] != x:
c += w[ix-1]
elif a[ix] != a[ix-1] == x:
c -= w[ix-1]
if ix != n-1:
if a[ix] == a[ix+1] != x:
c += w[ix]
elif {{completion}}:
c -= w[ix]
a[ix] = x
sys.stdout.write(str(c+(n*(n+1))//2) + '\n')
|
a[ix] != a[ix+1] == x
|
[{"input": "5 5\n1 2 3 4 5\n3 2\n4 2\n3 1\n2 1\n2 2", "output": ["29\n23\n35\n25\n35"]}]
|
control_completion_000082
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order: the root has index $$$1$$$; if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way: if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$; otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree: choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).
Input Specification: The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.
Output Specification: Print one integer — the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.
Code:
mod=998244353
cnt=0
n=int(input())
s=input()
import random
q=random.randint(10**9,2*10**9)
p=random.randint(10**9,2*10**9)
r=10**9+7
a=[-1]
for i in s:
if i=='A':
a.append(p)
else:
a.append(q)
for i in range(2**(n-1)-1,0,-1):
if # TODO: Your code here:
cnt+=1
a[i]=a[i]^(2*a[2*i]+2*a[2*i+1])
a[i]%=r
print(pow(2,cnt,mod))
|
mod=998244353
cnt=0
n=int(input())
s=input()
import random
q=random.randint(10**9,2*10**9)
p=random.randint(10**9,2*10**9)
r=10**9+7
a=[-1]
for i in s:
if i=='A':
a.append(p)
else:
a.append(q)
for i in range(2**(n-1)-1,0,-1):
if {{completion}}:
cnt+=1
a[i]=a[i]^(2*a[2*i]+2*a[2*i+1])
a[i]%=r
print(pow(2,cnt,mod))
|
a[2*i]!=a[2*i+1]
|
[{"input": "4\nBAAAAAAAABBABAB", "output": ["16"]}, {"input": "2\nBAA", "output": ["1"]}, {"input": "2\nABA", "output": ["2"]}, {"input": "2\nAAB", "output": ["2"]}, {"input": "2\nAAA", "output": ["1"]}]
|
control_completion_001664
|
control_fixed
|
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: You are given an integer $$$n$$$.Let's define $$$s(n)$$$ as the string "BAN" concatenated $$$n$$$ times. For example, $$$s(1)$$$ = "BAN", $$$s(3)$$$ = "BANBANBAN". Note that the length of the string $$$s(n)$$$ is equal to $$$3n$$$.Consider $$$s(n)$$$. You can perform the following operation on $$$s(n)$$$ any number of times (possibly zero): Select any two distinct indices $$$i$$$ and $$$j$$$ $$$(1 \leq i, j \leq 3n, i \ne j)$$$. Then, swap $$$s(n)_i$$$ and $$$s(n)_j$$$. You want the string "BAN" to not appear in $$$s(n)$$$ as a subsequence. What's the smallest number of operations you have to do to achieve this? Also, find one such shortest sequence of operations.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 100)$$$ — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 100)$$$.
Output Specification: For each test case, in the first line output $$$m$$$ ($$$0 \le m \le 10^5$$$) — the minimum number of operations required. It's guaranteed that the objective is always achievable in at most $$$10^5$$$ operations under the constraints of the problem. Then, output $$$m$$$ lines. The $$$k$$$-th of these lines should contain two integers $$$i_k$$$, $$$j_k$$$ $$$(1\leq i_k, j_k \leq 3n, i_k \ne j_k)$$$ denoting that you want to swap characters at indices $$$i_k$$$ and $$$j_k$$$ at the $$$k$$$-th operation. After all $$$m$$$ operations, "BAN" must not appear in $$$s(n)$$$ as a subsequence. If there are multiple possible answers, output any.
Notes: NoteIn the first testcase, $$$s(1) = $$$ "BAN", we can swap $$$s(1)_1$$$ and $$$s(1)_2$$$, converting $$$s(1)$$$ to "ABN", which does not contain "BAN" as a subsequence.In the second testcase, $$$s(2) = $$$ "BANBAN", we can swap $$$s(2)_2$$$ and $$$s(2)_6$$$, converting $$$s(2)$$$ to "BNNBAA", which does not contain "BAN" as a subsequence.
Code:
from sys import stdin
t = int(stdin.readline().strip())
for i in range(t):
n = int(stdin.readline().strip())
b = list('ban'*n)
if n==1:
print(1)
print(1, 2)
else:
z = n*3-1
print(n//2+n%2)
for i3 in range(n//2+n%2):
for i2 in range(n*3):
if b[i2]=='a':
# TODO: Your code here
|
from sys import stdin
t = int(stdin.readline().strip())
for i in range(t):
n = int(stdin.readline().strip())
b = list('ban'*n)
if n==1:
print(1)
print(1, 2)
else:
z = n*3-1
print(n//2+n%2)
for i3 in range(n//2+n%2):
for i2 in range(n*3):
if b[i2]=='a':
{{completion}}
|
c = b[z]
b[z] = 'a'
b[i2] = c
print(min(i2+1, z+1), max(i2+1, z+1))
z-=3
break
|
[{"input": "2\n1\n2", "output": ["1\n1 2\n1\n2 6"]}]
|
block_completion_001831
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) — the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$) — card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer — the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
ndfeagbb, dfeagbbk = map(int, input().split())
cards = [tuple(map(int, input().split())) for _ in range(ndfeagbb)]
cards_lookup, counter = {card: i for i, card in enumerate(cards)}, [0] * (ndfeagbb + 1)
for i in range(len(cards) - 1):
for j in range(i + 1, len(cards)):
# TODO: Your code here
print(sum(x * (x - 1) // 2 for x in counter[:-1]))
|
ndfeagbb, dfeagbbk = map(int, input().split())
cards = [tuple(map(int, input().split())) for _ in range(ndfeagbb)]
cards_lookup, counter = {card: i for i, card in enumerate(cards)}, [0] * (ndfeagbb + 1)
for i in range(len(cards) - 1):
for j in range(i + 1, len(cards)):
{{completion}}
print(sum(x * (x - 1) // 2 for x in counter[:-1]))
|
counter[cards_lookup.get(tuple(x if x == y else ((x + 1) ^ (y + 1)) - 1 for x, y in zip(cards[i], cards[j])), -1)] += 1
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005315
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer — the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for # TODO: Your code here:a,b,*_,c,d=sorted(map(int,s.split()));print(c+d-a-b)
|
for {{completion}}:a,b,*_,c,d=sorted(map(int,s.split()));print(c+d-a-b)
|
s in[*open(0)][2::2]
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
control_completion_005296
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $$$v$$$ (different from root) is the previous to $$$v$$$ vertex on the shortest path from the root to the vertex $$$v$$$. Children of the vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent.You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex $$$v$$$, if at least one child of $$$v$$$ is infected, you can spread the disease by infecting at most one other child of $$$v$$$ of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.
Input Specification: The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of the vertices in the given tree. The second line of each test case contains $$$n - 1$$$ integers $$$p_2, p_3, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ is the ancestor of the $$$i$$$-th vertex in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case you should output a single integer — the minimal number of seconds needed to infect the whole tree.
Notes: NoteThe image depicts the tree from the first test case during each second.A vertex is black if it is not infected. A vertex is blue if it is infected by injection during the previous second. A vertex is green if it is infected by spreading during the previous second. A vertex is red if it is infected earlier than the previous second. Note that you are able to choose which vertices are infected by spreading and by injections.
Code:
t = int(input())
for i in range(t):
n = int(input())
p = [int(value) for value in input().split()]
tree = [0] * n
for i in range(len(p)):
tree[p[i] - 1] += 1
tree = sorted(tree)
resposta = 0
r = n
while resposta <= r:
s = 0
c = 1
m = (resposta + r) // 2
neg1 = -1
for i in range(n + neg1, neg1, neg1):
if tree[i] == 0:
# TODO: Your code here
aux = tree[i] + s - m
c += max(0, aux)
s += 1
if m - s >= c:
r = m - 1
else:
resposta = m + 1
print(resposta)
|
t = int(input())
for i in range(t):
n = int(input())
p = [int(value) for value in input().split()]
tree = [0] * n
for i in range(len(p)):
tree[p[i] - 1] += 1
tree = sorted(tree)
resposta = 0
r = n
while resposta <= r:
s = 0
c = 1
m = (resposta + r) // 2
neg1 = -1
for i in range(n + neg1, neg1, neg1):
if tree[i] == 0:
{{completion}}
aux = tree[i] + s - m
c += max(0, aux)
s += 1
if m - s >= c:
r = m - 1
else:
resposta = m + 1
print(resposta)
|
break
|
[{"input": "5\n7\n1 1 1 2 2 4\n5\n5 5 1 4\n2\n1\n3\n3 1\n6\n1 1 1 1 1", "output": ["4\n4\n2\n3\n4"]}]
|
block_completion_004396
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given two arrays: an array $$$a$$$ consisting of $$$n$$$ zeros and an array $$$b$$$ consisting of $$$n$$$ integers.You can apply the following operation to the array $$$a$$$ an arbitrary number of times: choose some subsegment of $$$a$$$ of length $$$k$$$ and add the arithmetic progression $$$1, 2, \ldots, k$$$ to this subsegment — i. e. add $$$1$$$ to the first element of the subsegment, $$$2$$$ to the second element, and so on. The chosen subsegment should be inside the borders of the array $$$a$$$ (i.e., if the left border of the chosen subsegment is $$$l$$$, then the condition $$$1 \le l \le l + k - 1 \le n$$$ should be satisfied). Note that the progression added is always $$$1, 2, \ldots, k$$$ but not the $$$k, k - 1, \ldots, 1$$$ or anything else (i.e., the leftmost element of the subsegment always increases by $$$1$$$, the second element always increases by $$$2$$$ and so on).Your task is to find the minimum possible number of operations required to satisfy the condition $$$a_i \ge b_i$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$. Note that the condition $$$a_i \ge b_i$$$ should be satisfied for all elements at once.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$) — the number of elements in both arrays and the length of the subsegment, respectively. The second line of the input contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10^{12}$$$), where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.
Output Specification: Print one integer — the minimum possible number of operations required to satisfy the condition $$$a_i \ge b_i$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$.
Notes: NoteConsider the first example. In this test, we don't really have any choice, so we need to add at least five progressions to make the first element equals $$$5$$$. The array $$$a$$$ becomes $$$[5, 10, 15]$$$.Consider the second example. In this test, let's add one progression on the segment $$$[1; 3]$$$ and two progressions on the segment $$$[4; 6]$$$. Then, the array $$$a$$$ becomes $$$[1, 2, 3, 2, 4, 6]$$$.
Code:
n,k = map(int, input().split())
bb = list(map(int, input().split()))
ans = 0
sofar = 0
sumprog = 0
timeq = []
for ib,b in enumerate(bb[::-1]):
kk = min(k, n-ib)
time = (max(0,b-sofar)+kk-1)//kk
ans += time
timeq.append(time)
sumprog += time
if ib >= k:
# TODO: Your code here
sofar += kk*time
sofar -= sumprog
# print(time, sofar, timeq, sumprog)
print(ans)
|
n,k = map(int, input().split())
bb = list(map(int, input().split()))
ans = 0
sofar = 0
sumprog = 0
timeq = []
for ib,b in enumerate(bb[::-1]):
kk = min(k, n-ib)
time = (max(0,b-sofar)+kk-1)//kk
ans += time
timeq.append(time)
sumprog += time
if ib >= k:
{{completion}}
sofar += kk*time
sofar -= sumprog
# print(time, sofar, timeq, sumprog)
print(ans)
|
sumprog -= timeq[ib-k]
|
[{"input": "3 3\n5 4 6", "output": ["5"]}, {"input": "6 3\n1 2 3 2 2 3", "output": ["3"]}, {"input": "6 3\n1 2 4 1 2 3", "output": ["3"]}, {"input": "7 3\n50 17 81 25 42 39 96", "output": ["92"]}]
|
block_completion_003443
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
Input Specification: The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 5$$$) — number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) — the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
Output Specification: Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Code:
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n-1):
u, v = [int(t) for t in input().split()]
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
q = int(input())
for _ in range(q):
input()
S = [int(t)-1 for t in input().split()]
in_S = [0] * n
for v in S:
in_S[v] = 1
v = S[0]
w = farthest(g, v, in_S)
y = farthest(g, w, in_S)
P = set(path(g, w, y))
ans = "YES" if P.issuperset(S) else "NO"
print(ans)
def farthest(g, v, in_S):
queue = [v]
depth = [-1] * len(g)
depth[v] = 0
res = (0, v)
for v in queue:
if in_S[v]:
res = max(res, (depth[v], v))
for nei in g[v]:
if # TODO: Your code here:
queue.append(nei)
depth[nei] = depth[v] + 1
return res[1]
def path(g, st, en):
queue = [st]
prev = [-1] * len(g)
prev[st] = st
for v in queue:
for nei in g[v]:
if prev[nei] == -1:
queue.append(nei)
prev[nei] = v
res = [en]
while prev[res[-1]] != res[-1]:
res.append(prev[res[-1]])
return res[::-1]
import sys, os, io
input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
solve()
os.write(1, stdout.getvalue())
|
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n-1):
u, v = [int(t) for t in input().split()]
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
q = int(input())
for _ in range(q):
input()
S = [int(t)-1 for t in input().split()]
in_S = [0] * n
for v in S:
in_S[v] = 1
v = S[0]
w = farthest(g, v, in_S)
y = farthest(g, w, in_S)
P = set(path(g, w, y))
ans = "YES" if P.issuperset(S) else "NO"
print(ans)
def farthest(g, v, in_S):
queue = [v]
depth = [-1] * len(g)
depth[v] = 0
res = (0, v)
for v in queue:
if in_S[v]:
res = max(res, (depth[v], v))
for nei in g[v]:
if {{completion}}:
queue.append(nei)
depth[nei] = depth[v] + 1
return res[1]
def path(g, st, en):
queue = [st]
prev = [-1] * len(g)
prev[st] = st
for v in queue:
for nei in g[v]:
if prev[nei] == -1:
queue.append(nei)
prev[nei] = v
res = [en]
while prev[res[-1]] != res[-1]:
res.append(prev[res[-1]])
return res[::-1]
import sys, os, io
input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
solve()
os.write(1, stdout.getvalue())
|
depth[nei] == -1
|
[{"input": "5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "output": ["YES\nNO\nYES\nNO\nYES"]}, {"input": "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1", "output": ["YES\nNO\nYES\nYES"]}]
|
control_completion_002216
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.
Input Specification: The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$) — elements of given array.
Output Specification: In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.
Notes: NoteIn the first example $$$3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24$$$. Number $$$24$$$ is divisible by $$$4! = 24$$$.In the second example $$$3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18$$$, is divisible by $$$3! = 6$$$.In the third example $$$7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!$$$. It is easy to prove that this number is not divisible by $$$8!$$$.
Code:
n,x=map(int,input().split())
s={i:0 for i in range(1,x+1)}
def f(x,a):
s[x]=s[x]+a
an=map(int,input().split())
for b in an:
f(b,1)
l=1
i=1
while i < x:
if # TODO: Your code here:
f(i+1,s[i]//(i+1))
i+=1
else:
l=0
break
print(['no','yes'][l])
|
n,x=map(int,input().split())
s={i:0 for i in range(1,x+1)}
def f(x,a):
s[x]=s[x]+a
an=map(int,input().split())
for b in an:
f(b,1)
l=1
i=1
while i < x:
if {{completion}}:
f(i+1,s[i]//(i+1))
i+=1
else:
l=0
break
print(['no','yes'][l])
|
s[i]%(i+1)==0
|
[{"input": "6 4\n3 2 2 2 3 3", "output": ["Yes"]}, {"input": "8 3\n3 2 2 2 2 2 1 1", "output": ["Yes"]}, {"input": "7 8\n7 7 7 7 7 7 7", "output": ["No"]}, {"input": "10 5\n4 3 2 1 4 3 2 4 3 4", "output": ["No"]}, {"input": "2 500000\n499999 499999", "output": ["No"]}]
|
control_completion_005990
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$. Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the initial levels of trees moisture. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.
Output Specification: For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.
Notes: NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.
Code:
v = int(input())
while v > 0:
n = int(input())
arr = input().split()
ori = int(arr[0])
temp = 0
ans = 0
x = 1
while x < n:
nex = int(arr[x])
ans += abs(nex - ori)
if nex - ori < 0:
# TODO: Your code here
ori = nex
x += 1
ans += abs(int(arr[0]) - temp)
print(ans)
v -= 1
|
v = int(input())
while v > 0:
n = int(input())
arr = input().split()
ori = int(arr[0])
temp = 0
ans = 0
x = 1
while x < n:
nex = int(arr[x])
ans += abs(nex - ori)
if nex - ori < 0:
{{completion}}
ori = nex
x += 1
ans += abs(int(arr[0]) - temp)
print(ans)
v -= 1
|
temp += abs(nex - ori)
|
[{"input": "4\n3\n-2 -2 -2\n3\n10 4 7\n4\n4 -4 4 -4\n5\n1 -2 3 -4 5", "output": ["2\n13\n36\n33"]}]
|
block_completion_004204
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Recently in Divanovo, a huge river locks system was built. There are now $$$n$$$ locks, the $$$i$$$-th of them has the volume of $$$v_i$$$ liters, so that it can contain any amount of water between $$$0$$$ and $$$v_i$$$ liters. Each lock has a pipe attached to it. When the pipe is open, $$$1$$$ liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $$$i$$$ to the lock $$$i + 1$$$. If the lock $$$i + 1$$$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $$$5$$$ locks with two open pipes at locks $$$1$$$ and $$$3$$$. Because locks $$$1$$$, $$$3$$$, and $$$4$$$ are already filled, effectively the water goes to locks $$$2$$$ and $$$5$$$. Note that the volume of the $$$i$$$-th lock may be greater than the volume of the $$$i + 1$$$-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $$$q$$$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $$$j$$$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $$$t_j$$$ seconds.Please help the mayor to solve this tricky problem and answer his queries.
Input Specification: The first lines contains one integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of locks. The second lines contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$1 \le v_i \le 10^9$$$)) — volumes of the locks. The third line contains one integer $$$q$$$ ($$$1 \le q \le 200\,000$$$) — the number of queries. Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \le t_j \le 10^9$$$) — the number of seconds you have to fill all the locks in the query $$$j$$$.
Output Specification: Print $$$q$$$ integers. The $$$j$$$-th of them should be equal to the minimum number of pipes to turn on so that after $$$t_j$$$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $$$-1$$$.
Notes: NoteThere are $$$6$$$ queries in the first example test. In the queries $$$1, 3, 4$$$ the answer is $$$-1$$$. We need to wait $$$4$$$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$. After $$$4$$$ seconds the locks $$$1$$$ and $$$4$$$ are full. In the following $$$1$$$ second $$$1$$$ liter of water is transferred to the locks $$$2$$$ and $$$5$$$. The lock $$$3$$$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$.In the fifth query one can open pipes $$$1, 2, 3, 4$$$.
Code:
n = int(input())
a = list(map(int, input().split()))
maxi = tot = 0
for i, j in enumerate(a, 1):
tot += j
maxi = max(maxi, (tot+i-1) // i)
q = int(input())
for _ in range(q):
k = int(input())
if k < maxi:
print(-1)
else:
# open x pipe
# time = ceil(sum / x) => x increased => time decrease
# => sum <= x * time -> x >= sum / time -> x = ceil(sum / time) (looking for x min)
# TODO: Your code here
|
n = int(input())
a = list(map(int, input().split()))
maxi = tot = 0
for i, j in enumerate(a, 1):
tot += j
maxi = max(maxi, (tot+i-1) // i)
q = int(input())
for _ in range(q):
k = int(input())
if k < maxi:
print(-1)
else:
# open x pipe
# time = ceil(sum / x) => x increased => time decrease
# => sum <= x * time -> x >= sum / time -> x = ceil(sum / time) (looking for x min)
{{completion}}
|
print((tot + k - 1) // k)
|
[{"input": "5\n4 1 5 4 1\n6\n1\n6\n2\n3\n4\n5", "output": ["-1\n3\n-1\n-1\n4\n3"]}, {"input": "5\n4 4 4 4 4\n6\n1\n3\n6\n5\n2\n4", "output": ["-1\n-1\n4\n4\n-1\n5"]}]
|
block_completion_004267
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) — the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$) — the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.
Notes: NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.
Code:
def canmake(s,a,b,c,d):
anum = s.count('A')
bnum = s.count('B')
cnum = s.count('AB')
dnum = s.count('BA')
if cnum < c or dnum < d or anum != a + c + d or bnum != b + c + d:
return False
n=len(s)
ans=0
abls=[]
bals=[]
l=0
while l<n:
while l<n-1 and s[l]==s[l+1]:
l+=1
r=l
while r<n-1 and s[r]!=s[r+1]:
r+=1
if # TODO: Your code here:
ans+=(r-l+1)//2
if s[l]==s[r]=='A':
ans+=(r-l+1)//2
if s[l]=='A' and s[r]=='B':
abls.append((r-l+1)//2)
if s[l]=='B' and s[r]=='A':
bals.append((r-l+1)//2)
l=r+1
abls.sort()
bals.sort()
for i in abls:
if i<=c:
c-=i
else:
d-=i-c-1
c = 0
for i in bals:
if i<=d:
d-=i
else:
c-=i-d-1
d = 0
return (c+d)<=ans
t=int(input())
for _ in range(t):
a,b,c,d=[int(x) for x in input().split()]
s=input()
res=canmake(s,a,b,c,d)
if res:
print('YES')
else:
print('NO')
|
def canmake(s,a,b,c,d):
anum = s.count('A')
bnum = s.count('B')
cnum = s.count('AB')
dnum = s.count('BA')
if cnum < c or dnum < d or anum != a + c + d or bnum != b + c + d:
return False
n=len(s)
ans=0
abls=[]
bals=[]
l=0
while l<n:
while l<n-1 and s[l]==s[l+1]:
l+=1
r=l
while r<n-1 and s[r]!=s[r+1]:
r+=1
if {{completion}}:
ans+=(r-l+1)//2
if s[l]==s[r]=='A':
ans+=(r-l+1)//2
if s[l]=='A' and s[r]=='B':
abls.append((r-l+1)//2)
if s[l]=='B' and s[r]=='A':
bals.append((r-l+1)//2)
l=r+1
abls.sort()
bals.sort()
for i in abls:
if i<=c:
c-=i
else:
d-=i-c-1
c = 0
for i in bals:
if i<=d:
d-=i
else:
c-=i-d-1
d = 0
return (c+d)<=ans
t=int(input())
for _ in range(t):
a,b,c,d=[int(x) for x in input().split()]
s=input()
res=canmake(s,a,b,c,d)
if res:
print('YES')
else:
print('NO')
|
s[l]== s[r]=='B'
|
[{"input": "8\n1 0 0 0\nB\n0 0 1 0\nAB\n1 1 0 1\nABAB\n1 0 1 1\nABAAB\n1 1 2 2\nBAABBABBAA\n1 1 2 3\nABABABBAABAB\n2 3 5 4\nAABAABBABAAABABBABBBABB\n1 3 3 10\nBBABABABABBBABABABABABABAABABA", "output": ["NO\nYES\nYES\nYES\nYES\nYES\nNO\nYES"]}]
|
control_completion_001184
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells: An empty cell, denoted with '.'. A stone, denoted with '*'. An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?
Input Specification: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o' — an empty cell, a stone, or an obstacle, respectively.
Output Specification: For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.
Code:
for _ in range(int(input())):
n, _ = map(int, input().split())
a = map("".join, zip(*(input() for _ in range(n))))
a = ("o".join("".join(sorted(y, reverse=True)) for y in x.split("o")) for x in a)
for # TODO: Your code here:
print("".join(x))
|
for _ in range(int(input())):
n, _ = map(int, input().split())
a = map("".join, zip(*(input() for _ in range(n))))
a = ("o".join("".join(sorted(y, reverse=True)) for y in x.split("o")) for x in a)
for {{completion}}:
print("".join(x))
|
x in zip(*a)
|
[{"input": "3\n6 10\n.*.*....*.\n.*.......*\n...o....o.\n.*.*....*.\n..........\n.o......o*\n2 9\n...***ooo\n.*o.*o.*o\n5 5\n*****\n*....\n*****\n....*\n*****", "output": ["..........\n...*....*.\n.*.o....o.\n.*........\n.*......**\n.o.*....o*\n\n....**ooo\n.*o**o.*o\n\n.....\n*...*\n*****\n*****\n*****"]}]
|
control_completion_000829
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
for _ in range(int(input())):
l=[]
ans="B"
while len(l)!=8:
l.append(input())
if len(l[-1])<8:
l.pop()
for row in l:
if row.count('R')==8:
# TODO: Your code here
print(ans)
|
for _ in range(int(input())):
l=[]
ans="B"
while len(l)!=8:
l.append(input())
if len(l[-1])<8:
l.pop()
for row in l:
if row.count('R')==8:
{{completion}}
print(ans)
|
ans='R'
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005804
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given two arrays $$$a$$$ and $$$b$$$, consisting of $$$n$$$ integers each.Let's define a function $$$f(a, b)$$$ as follows: let's define an array $$$c$$$ of size $$$n$$$, where $$$c_i = a_i \oplus b_i$$$ ($$$\oplus$$$ denotes bitwise XOR); the value of the function is $$$c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n$$$ (i.e. bitwise AND of the entire array $$$c$$$). Find the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way (leaving the initial order is also an option).
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 2^{30}$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i < 2^{30}$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case print one integer — the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way.
Code:
import sys
from itertools import permutations, combinations
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
ls.append(lst)
def solve(n, a, b):
ps = [((list(range(n))), (list(range(n))))]
res = (1<<30) - 1
for k in range(30, -1, -1):
next_ps = []
for (pa, pb) in ps:
a0, a1, b0, b1 = [], [], [], []
for pai in pa:
if a[pai] & (1<<k) == 0: a0.append(pai)
else: # TODO: Your code here
for pbi in pb:
if b[pbi] & (1<<k) == 0: b0.append(pbi)
else: b1.append(pbi)
if len(a0) == len(b1):
res = res & (res | (1 << k))
if len(a0) > 0 and len(b1) > 0: next_ps.append((a0, b1))
if len(a1) > 0 and len(b0) > 0: next_ps.append((a1, b0))
else:
res = res & ~(1 << k)
next_ps.append((pa, pb))
ps = next_ps if int(res & (1<<k)) != 0 else ps
return res
#return rec(a, b, max_order-1)
for i in range(1, len(ls)-1, 3):
n = int(ls[i])
a = [int(x) for x in ls[i+1].split(' ')]
b = [int(x) for x in ls[i+2].split(' ')]
print(solve(n, a, b))
|
import sys
from itertools import permutations, combinations
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
ls.append(lst)
def solve(n, a, b):
ps = [((list(range(n))), (list(range(n))))]
res = (1<<30) - 1
for k in range(30, -1, -1):
next_ps = []
for (pa, pb) in ps:
a0, a1, b0, b1 = [], [], [], []
for pai in pa:
if a[pai] & (1<<k) == 0: a0.append(pai)
else: {{completion}}
for pbi in pb:
if b[pbi] & (1<<k) == 0: b0.append(pbi)
else: b1.append(pbi)
if len(a0) == len(b1):
res = res & (res | (1 << k))
if len(a0) > 0 and len(b1) > 0: next_ps.append((a0, b1))
if len(a1) > 0 and len(b0) > 0: next_ps.append((a1, b0))
else:
res = res & ~(1 << k)
next_ps.append((pa, pb))
ps = next_ps if int(res & (1<<k)) != 0 else ps
return res
#return rec(a, b, max_order-1)
for i in range(1, len(ls)-1, 3):
n = int(ls[i])
a = [int(x) for x in ls[i+1].split(' ')]
b = [int(x) for x in ls[i+2].split(' ')]
print(solve(n, a, b))
|
a1.append(pai)
|
[{"input": "3\n\n5\n\n1 0 0 3 3\n\n2 3 2 1 0\n\n3\n\n1 1 1\n\n0 0 3\n\n8\n\n0 1 2 3 4 5 6 7\n\n7 6 5 4 3 2 1 0", "output": ["2\n0\n7"]}]
|
block_completion_002743
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: The Narrator has an integer array $$$a$$$ of length $$$n$$$, but he will only tell you the size $$$n$$$ and $$$q$$$ statements, each of them being three integers $$$i, j, x$$$, which means that $$$a_i \mid a_j = x$$$, where $$$|$$$ denotes the bitwise OR operation.Find the lexicographically smallest array $$$a$$$ that satisfies all the statements.An array $$$a$$$ is lexicographically smaller than an array $$$b$$$ of the same length if and only if the following holds: in the first position where $$$a$$$ and $$$b$$$ differ, the array $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.
Input Specification: In the first line you are given with two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). In the next $$$q$$$ lines you are given with three integers $$$i$$$, $$$j$$$, and $$$x$$$ ($$$1 \le i, j \le n$$$, $$$0 \le x < 2^{30}$$$) — the statements. It is guaranteed that all $$$q$$$ statements hold for at least one array.
Output Specification: On a single line print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{30}$$$) — array $$$a$$$.
Notes: NoteIn the first sample, these are all the arrays satisfying the statements: $$$[0, 3, 2, 2]$$$, $$$[2, 1, 0, 0]$$$, $$$[2, 1, 0, 2]$$$, $$$[2, 1, 2, 0]$$$, $$$[2, 1, 2, 2]$$$, $$$[2, 3, 0, 0]$$$, $$$[2, 3, 0, 2]$$$, $$$[2, 3, 2, 0]$$$, $$$[2, 3, 2, 2]$$$.
Code:
from sys import stdin, stdout
input, print = stdin.buffer.readline, stdout.write
n, T = [int(x) for x in input().split()]
ans = [(1<<31)-1] * n
from collections import defaultdict
R = defaultdict(list)
for _ in range(T):
a,b, x = [int(_a) for _a in input().split()]
a -= 1
b -= 1
a,b = min(a,b), max(a,b)
ans[a] &= x
ans[b] &= x
R[a].append(b)
R[b].append(a)
for i in range(len(ans)):
for b in range(30,-1,-1):
mask = 1 << b
if mask & ans[i] == 0:
continue
can_remove = True
for j in R[i]:
if # TODO: Your code here:
can_remove = False
break
if can_remove:
ans[i] ^= mask
print(" ".join(str(x)for x in ans)+"\n")
|
from sys import stdin, stdout
input, print = stdin.buffer.readline, stdout.write
n, T = [int(x) for x in input().split()]
ans = [(1<<31)-1] * n
from collections import defaultdict
R = defaultdict(list)
for _ in range(T):
a,b, x = [int(_a) for _a in input().split()]
a -= 1
b -= 1
a,b = min(a,b), max(a,b)
ans[a] &= x
ans[b] &= x
R[a].append(b)
R[b].append(a)
for i in range(len(ans)):
for b in range(30,-1,-1):
mask = 1 << b
if mask & ans[i] == 0:
continue
can_remove = True
for j in R[i]:
if {{completion}}:
can_remove = False
break
if can_remove:
ans[i] ^= mask
print(" ".join(str(x)for x in ans)+"\n")
|
i == j or mask & ans[j] == 0
|
[{"input": "4 3\n1 2 3\n1 3 2\n4 1 2", "output": ["0 3 2 2"]}, {"input": "1 0", "output": ["0"]}, {"input": "2 1\n1 1 1073741823", "output": ["1073741823 0"]}]
|
control_completion_000019
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: A triple of points $$$i$$$, $$$j$$$ and $$$k$$$ on a coordinate line is called beautiful if $$$i < j < k$$$ and $$$k - i \le d$$$.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set.
Input Specification: The first line contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q, d \le 2 \cdot 10^5$$$) — the number of queries and the parameter for defining if a triple is beautiful, respectively. The second line contains $$$q$$$ integers $$$a_1, a_2, \dots, a_q$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) denoting the queries. The integer $$$a_i$$$ denotes the $$$i$$$-th query in the following way: if the point $$$a_i$$$ belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples.
Output Specification: For each query, print one integer — the number of beautiful triples after processing the respective query.
Code:
import sys
# https://codeforces.com/contest/1701/problem/F
MAXN = 200000
class SegmentTree:
def __init__(self):
self.lazy = []
self.v0 = []
self.v1 = []
self.v2 = []
self.active = []
for # TODO: Your code here:
self.lazy.append(0)
self.v0.append(1)
self.v1.append(0)
self.v2.append(0)
self.active.append(True)
self._init_active(1, 1, MAXN)
def _init_active(self, x, l, r):
if l == r:
self.active[x] = False
else:
m = (l + r) // 2
self._init_active(x * 2, l, m)
self._init_active(x * 2 + 1, m + 1, r)
self._reclac(x)
def _reclac(self, x):
self.v0[x] = 0
self.v1[x] = 0
self.v2[x] = 0
if self.active[x * 2]:
self.v0[x] += self.v0[x * 2]
self.v1[x] += self.v1[x * 2]
self.v2[x] += self.v2[x * 2]
if self.active[x * 2 + 1]:
self.v0[x] += self.v0[x * 2 + 1]
self.v1[x] += self.v1[x * 2 + 1]
self.v2[x] += self.v2[x * 2 + 1]
def _push(self, x, l, r):
la = self.lazy[x]
if la == 0:
return
if l != r:
self.v2[x * 2] = self.v2[x * 2] + 2 * la * self.v1[x * 2] + la * la * self.v0[x * 2]
self.v1[x * 2] += la * self.v0[x * 2]
self.v2[x * 2 + 1] = self.v2[x * 2 + 1] + 2 * la * self.v1[x * 2 + 1] + la * la * self.v0[x * 2 + 1]
self.v1[x * 2 + 1] += la * self.v0[x * 2 + 1]
self.lazy[x * 2] += la
self.lazy[x * 2 + 1] += la
self.lazy[x] = 0
def update(self, x, l, r, a, b, up: bool):
if r < a or b < l:
return
if a <= l and r <= b:
if up:
self.v2[x] = self.v2[x] + 2 * self.v1[x] + self.v0[x]
self.v1[x] += self.v0[x]
self.lazy[x] += 1
else:
self.v2[x] = self.v2[x] - 2 * self.v1[x] + self.v0[x]
self.v1[x] -= self.v0[x]
self.lazy[x] -= 1
return
m = (l + r) // 2
self._push(x, l, r)
self.update(x * 2, l, m, a, b, up)
self.update(x * 2 + 1, m + 1, r, a, b, up)
self._reclac(x)
def set_state(self, x, l, r, pos, up: bool):
if pos < l or r < pos:
return
if l == r:
self.active[x] = up
return
m = (l + r) // 2
self._push(x, l, r)
self.set_state(x * 2, l, m, pos, up)
self.set_state(x * 2 + 1, m + 1, r, pos, up)
self._reclac(x)
def solve():
q, d = map(int, input().split())
points = map(int, sys.stdin.readline().split())
tree = SegmentTree()
check = [0] * (MAXN + 1)
ans = []
for point in points:
if check[point]:
check[point] = 0
tree.update(1, 1, MAXN, max(1, point - d), point - 1, False)
tree.set_state(1, 1, MAXN, point, False)
else:
check[point] = 1
tree.update(1, 1, MAXN, max(1, point - d), point - 1, True)
tree.set_state(1, 1, MAXN, point, True)
v1 = tree.v1[1]
v2 = tree.v2[1]
ans.append((v2 - v1) // 2)
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
solve()
|
import sys
# https://codeforces.com/contest/1701/problem/F
MAXN = 200000
class SegmentTree:
def __init__(self):
self.lazy = []
self.v0 = []
self.v1 = []
self.v2 = []
self.active = []
for {{completion}}:
self.lazy.append(0)
self.v0.append(1)
self.v1.append(0)
self.v2.append(0)
self.active.append(True)
self._init_active(1, 1, MAXN)
def _init_active(self, x, l, r):
if l == r:
self.active[x] = False
else:
m = (l + r) // 2
self._init_active(x * 2, l, m)
self._init_active(x * 2 + 1, m + 1, r)
self._reclac(x)
def _reclac(self, x):
self.v0[x] = 0
self.v1[x] = 0
self.v2[x] = 0
if self.active[x * 2]:
self.v0[x] += self.v0[x * 2]
self.v1[x] += self.v1[x * 2]
self.v2[x] += self.v2[x * 2]
if self.active[x * 2 + 1]:
self.v0[x] += self.v0[x * 2 + 1]
self.v1[x] += self.v1[x * 2 + 1]
self.v2[x] += self.v2[x * 2 + 1]
def _push(self, x, l, r):
la = self.lazy[x]
if la == 0:
return
if l != r:
self.v2[x * 2] = self.v2[x * 2] + 2 * la * self.v1[x * 2] + la * la * self.v0[x * 2]
self.v1[x * 2] += la * self.v0[x * 2]
self.v2[x * 2 + 1] = self.v2[x * 2 + 1] + 2 * la * self.v1[x * 2 + 1] + la * la * self.v0[x * 2 + 1]
self.v1[x * 2 + 1] += la * self.v0[x * 2 + 1]
self.lazy[x * 2] += la
self.lazy[x * 2 + 1] += la
self.lazy[x] = 0
def update(self, x, l, r, a, b, up: bool):
if r < a or b < l:
return
if a <= l and r <= b:
if up:
self.v2[x] = self.v2[x] + 2 * self.v1[x] + self.v0[x]
self.v1[x] += self.v0[x]
self.lazy[x] += 1
else:
self.v2[x] = self.v2[x] - 2 * self.v1[x] + self.v0[x]
self.v1[x] -= self.v0[x]
self.lazy[x] -= 1
return
m = (l + r) // 2
self._push(x, l, r)
self.update(x * 2, l, m, a, b, up)
self.update(x * 2 + 1, m + 1, r, a, b, up)
self._reclac(x)
def set_state(self, x, l, r, pos, up: bool):
if pos < l or r < pos:
return
if l == r:
self.active[x] = up
return
m = (l + r) // 2
self._push(x, l, r)
self.set_state(x * 2, l, m, pos, up)
self.set_state(x * 2 + 1, m + 1, r, pos, up)
self._reclac(x)
def solve():
q, d = map(int, input().split())
points = map(int, sys.stdin.readline().split())
tree = SegmentTree()
check = [0] * (MAXN + 1)
ans = []
for point in points:
if check[point]:
check[point] = 0
tree.update(1, 1, MAXN, max(1, point - d), point - 1, False)
tree.set_state(1, 1, MAXN, point, False)
else:
check[point] = 1
tree.update(1, 1, MAXN, max(1, point - d), point - 1, True)
tree.set_state(1, 1, MAXN, point, True)
v1 = tree.v1[1]
v2 = tree.v2[1]
ans.append((v2 - v1) // 2)
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
solve()
|
_ in range(4 * MAXN + 1)
|
[{"input": "7 5\n8 5 3 2 1 5 6", "output": ["0\n0\n1\n2\n5\n1\n5"]}]
|
control_completion_005125
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) — the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) — the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) — the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if # TODO: Your code here:f=1
if d[l[cur][1]]==2:break
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if {{completion}}:f=1
if d[l[cur][1]]==2:break
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
l[cur][2]!=0 or l[cur][1]==l[cur][0]
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
control_completion_005927
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones. You can do the following operation: choose two indices $$$1 \le i , j \le n$$$, $$$i \ne j$$$, add $$$a_{i}$$$ to $$$a_{j}$$$, remove $$$a_{i}$$$ from $$$a$$$. Note that elements of $$$a$$$ can become bigger than $$$1$$$ after performing some operations. Also note that $$$n$$$ becomes $$$1$$$ less after the operation.What is the minimum number of operations needed to make $$$a$$$ non-decreasing, i. e. that each element is not less than the previous element?
Input Specification: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the size of array $$$a$$$. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$. It's guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
Output Specification: For each test case print a single integer, minimum number of operations needed to make $$$a$$$ non-decreasing.
Notes: NoteIn the first test case, $$$a$$$ is already non-decreasing, so you don't need to do any operations and the answer is $$$0$$$.In the second test case, you can perform an operation for $$$i = 1$$$ and $$$j = 5$$$, so $$$a$$$ will be equal to $$$[0, 0, 1, 2]$$$ and it becomes non-decreasing.In the third test case, you can perform an operation for $$$i = 2$$$ and $$$j = 1$$$, so $$$a$$$ will be equal to $$$[1]$$$ and it becomes non-decreasing.
Code:
import sys
tokens = (token for token in sys.stdin.read().split())
N = int(next(tokens))
for i in range(N):
Q = int(next(tokens))
arr = []
count = 0
for i in range(Q):
arr.append(int(next(tokens)))
i = 0
j = len(arr) - 1
while True:
while True:
if arr[i] == 1 or i == j:
break
else:
i+=1
while True:
if # TODO: Your code here:
break
else:
j-=1
if i == j:
break
sec = arr[i]
arr [i] = arr[j]
arr [j] = sec
count += 1
print (count)
|
import sys
tokens = (token for token in sys.stdin.read().split())
N = int(next(tokens))
for i in range(N):
Q = int(next(tokens))
arr = []
count = 0
for i in range(Q):
arr.append(int(next(tokens)))
i = 0
j = len(arr) - 1
while True:
while True:
if arr[i] == 1 or i == j:
break
else:
i+=1
while True:
if {{completion}}:
break
else:
j-=1
if i == j:
break
sec = arr[i]
arr [i] = arr[j]
arr [j] = sec
count += 1
print (count)
|
arr[j] == 0 or j == i
|
[{"input": "4\n\n8\n\n0 0 1 1 1 1 1 1\n\n5\n\n1 0 0 1 1\n\n2\n\n1 0\n\n11\n\n1 1 0 0 1 0 0 1 1 1 0", "output": ["0\n1\n1\n3"]}]
|
control_completion_006842
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns with each cell having a non-negative integer written on it. Timur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is maximal. The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. Help him find the maximal sum he can get.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 200$$$, $$$1 \leq m \leq 200$$$). The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element of the $$$i$$$-th line $$$a_{ij}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row $$$(0\leq a_{ij} \leq 10^6)$$$ It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$4\cdot10^4$$$.
Output Specification: For each test case output a single integer, the maximum sum over all possible placements of the bishop.
Notes: NoteFor the first test case here the best sum is achieved by the bishop being in this position:
Code:
t=int(input())
for p in range(t):
n,m=map(int,input().split())
c=[]
b=[]
s=0
for i in range(n):
a=list(map(int,input().split()))
b+=[a]
for k in range(n):
for l in range(m):
for v in range(min(l,k)+1):
# TODO: Your code here
for w in range(1,min(n-k-1,m-l-1)+1):
s+=b[k+w][l+w]
for i1 in range(1,min(k,m-l-1)+1):
s+=b[k-i1][l+i1]
for j1 in range(1,min(n-k-1,l)+1):
s+=b[k+j1][l-j1]
c+=[s]
s=0
print(max(c))
|
t=int(input())
for p in range(t):
n,m=map(int,input().split())
c=[]
b=[]
s=0
for i in range(n):
a=list(map(int,input().split()))
b+=[a]
for k in range(n):
for l in range(m):
for v in range(min(l,k)+1):
{{completion}}
for w in range(1,min(n-k-1,m-l-1)+1):
s+=b[k+w][l+w]
for i1 in range(1,min(k,m-l-1)+1):
s+=b[k-i1][l+i1]
for j1 in range(1,min(n-k-1,l)+1):
s+=b[k+j1][l-j1]
c+=[s]
s=0
print(max(c))
|
s+=b[k-v][l-v]
|
[{"input": "4\n4 4\n1 2 2 1\n2 4 2 4\n2 2 3 1\n2 4 2 4\n2 1\n1\n0\n3 3\n1 1 1\n1 1 1\n1 1 1\n3 3\n0 1 1\n1 0 1\n1 1 0", "output": ["20\n1\n5\n3"]}]
|
block_completion_007701
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i > 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i < i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty): Choose a card $$$x$$$ such that no other cards are hanging onto it. Append the number written on card $$$x$$$ to the end of $$$s$$$. If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$. Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
Input Specification: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) describing which card that each card hangs onto.
Output Specification: Print a single integer — the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.
Notes: NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order: Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 > w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$. Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$. Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$. Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 > w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$. Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$. Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.
Code:
n=int(input())
a=[-1]+[int(o)-1 for o in input().split()]
f=[0]*n
dp=[0]*n
for i in range(n-1,0,-1):
f[a[i]]=max(f[i]+1,f[a[i]])
for i in range(n-1,0,-1):
# TODO: Your code here
print(max(dp[0],f[0]+1))
|
n=int(input())
a=[-1]+[int(o)-1 for o in input().split()]
f=[0]*n
dp=[0]*n
for i in range(n-1,0,-1):
f[a[i]]=max(f[i]+1,f[a[i]])
for i in range(n-1,0,-1):
{{completion}}
print(max(dp[0],f[0]+1))
|
dp[i]=max(dp[i],f[i]+1)
dp[a[i]]+=dp[i]
|
[{"input": "6\n1 2 1 4 2", "output": ["4"]}, {"input": "2\n1", "output": ["2"]}]
|
block_completion_004727
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
Output Specification: Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
Notes: NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
Code:
import heapq as hq
INF = 1001001001
N, M = map(int, input().split())
G = [[] for _ in range(N)]
d = [0] * N
for _ in range(M):
U, V = map(int, input().split())
G[V - 1].append(U - 1)
d[U - 1] += 1
dists = [INF] * N
dists[N - 1] = 0
queue = [(0, N - 1)]
while queue:
dist, V = hq.heappop(queue)
if dists[V] < dist: continue
for v in G[V]:
if # TODO: Your code here:
dists[v] = dist + d[v]
hq.heappush(queue, (dist + d[v], v))
d[v] -= 1
print(dists[0])
|
import heapq as hq
INF = 1001001001
N, M = map(int, input().split())
G = [[] for _ in range(N)]
d = [0] * N
for _ in range(M):
U, V = map(int, input().split())
G[V - 1].append(U - 1)
d[U - 1] += 1
dists = [INF] * N
dists[N - 1] = 0
queue = [(0, N - 1)]
while queue:
dist, V = hq.heappop(queue)
if dists[V] < dist: continue
for v in G[V]:
if {{completion}}:
dists[v] = dist + d[v]
hq.heappush(queue, (dist + d[v], v))
d[v] -= 1
print(dists[0])
|
dist + d[v] < dists[v]
|
[{"input": "2 1\n1 2", "output": ["1"]}, {"input": "4 4\n1 2\n1 4\n2 4\n1 4", "output": ["2"]}, {"input": "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1", "output": ["4"]}]
|
control_completion_000462
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: You have an array $$$a$$$ consisting of $$$n$$$ positive integers and you have to handle $$$q$$$ queries of the following types: $$$1$$$ $$$i$$$ $$$x$$$: change $$$a_{i}$$$ to $$$x$$$, $$$2$$$ $$$l$$$ $$$r$$$ $$$k$$$: check if the number of occurrences of every positive integer in the subarray $$$a_{l}, a_{l+1}, \ldots a_{r}$$$ is a multiple of $$$k$$$ (check the example for better understanding).
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n , q \le 3 \cdot 10^5$$$), the length of $$$a$$$ and the number of queries. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots a_{n}$$$ ($$$1 \le a_{i} \le 10^9$$$) — the elements of $$$a$$$. Each of the next $$$q$$$ lines describes a query. It has one of the following forms. $$$1$$$ $$$i$$$ $$$x$$$, ($$$1 \le i \le n$$$ , $$$1 \le x \le 10^9$$$), or $$$2$$$ $$$l$$$ $$$r$$$ $$$k$$$, ($$$1 \le l \le r \le n$$$ , $$$1 \le k \le n$$$).
Output Specification: For each query of the second type, if answer of the query is yes, print "YES", otherwise print "NO".
Notes: NoteIn the first query, requested subarray is $$$[1234, 2, 3, 3, 2, 1]$$$, and it's obvious that the number of occurrence of $$$1$$$ isn't divisible by $$$k = 2$$$. So the answer is "NO".In the third query, requested subarray is $$$[1, 2, 3, 3, 2, 1]$$$, and it can be seen that the number of occurrence of every integer in this sub array is divisible by $$$k = 2$$$. So the answer is "YES".In the sixth query, requested subarray is $$$[1, 2, 3, 3, 2, 1, 1, 2, 3]$$$, and it can be seen that the number of occurrence of every integer in this sub array is divisible by $$$k = 3$$$. So the answer is "YES".
Code:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
import random
class Bit:
def __init__(self, n):
self.size = n
self.n0 = 1 << (n.bit_length() - 1)
self.tree = [0] * (n + 1)
def range_sum(self, l, r):
return self.sum(r - 1) - self.sum(l - 1)
def sum(self, i):
i += 1
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def get(self, i):
return self.sum(i) - self.sum(i - 1)
def add(self, i, x):
i += 1
while i <= self.size:
self.tree[i] += x
i += i & -i
def lower_bound(self, x):
pos = 0
plus = self.n0
while plus > 0:
if pos + plus <= self.size and self.tree[pos + plus] < x:
x -= self.tree[pos + plus]
pos += plus
plus //= 2
return pos
def solve():
n, Q = map(int, input().split())
A = list(map(int, input().split()))
query = []
se = set(A)
ind = 0
ans = ["YES"] * Q
for _ in range(Q):
q = list(map(int, input().split()))
if q[0] == 2:
l, r, k = q[1:]
if (r - l + 1) % k != 0:
ans[ind] = "NO"
ind += 1
continue
q.append(ind)
ind += 1
else:
q[1] -= 1
query.append(q)
if q[0] == 1:
se.add(q[2])
ans = ans[:ind]
dic = {a:i for i, a in enumerate(sorted(se))}
A = [dic[a] for a in A]
for q in query:
if q[0] == 1:
q[2] = dic[q[2]]
m = len(se)
itr = 12
for _ in range(itr):
P = random.choices(range(4), k=m)
bit = Bit(n)
B = A[:]
for i, a in enumerate(A):
add = 0
if P[a] & 1:
add |= 1
if P[a] & 2:
add |= 1 << 30
if add != 0:
bit.add(i, add)
for q in query:
if q[0] == 1:
i, x = q[1:]
b = B[i]
B[i] = x
add = 0
if P[b] & 1:
add -= 1
if P[b] & 2:
add -= 1 << 30
if P[x] & 1:
add += 1
if P[x] & 2:
add += 1 << 30
if add != 0:
bit.add(i, add)
else:
l, r, k, i = q[1:]
if ans[i] == "NO":
# TODO: Your code here
c = bit.range_sum(l - 1, r)
if c % k != 0:
ans[i] = "NO"
elif (c >> 30) % k != 0:
ans[i] = "NO"
print(*ans, sep="\n")
T = 1
# T = int(input())
for t in range(1, T + 1):
solve()
|
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
import random
class Bit:
def __init__(self, n):
self.size = n
self.n0 = 1 << (n.bit_length() - 1)
self.tree = [0] * (n + 1)
def range_sum(self, l, r):
return self.sum(r - 1) - self.sum(l - 1)
def sum(self, i):
i += 1
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def get(self, i):
return self.sum(i) - self.sum(i - 1)
def add(self, i, x):
i += 1
while i <= self.size:
self.tree[i] += x
i += i & -i
def lower_bound(self, x):
pos = 0
plus = self.n0
while plus > 0:
if pos + plus <= self.size and self.tree[pos + plus] < x:
x -= self.tree[pos + plus]
pos += plus
plus //= 2
return pos
def solve():
n, Q = map(int, input().split())
A = list(map(int, input().split()))
query = []
se = set(A)
ind = 0
ans = ["YES"] * Q
for _ in range(Q):
q = list(map(int, input().split()))
if q[0] == 2:
l, r, k = q[1:]
if (r - l + 1) % k != 0:
ans[ind] = "NO"
ind += 1
continue
q.append(ind)
ind += 1
else:
q[1] -= 1
query.append(q)
if q[0] == 1:
se.add(q[2])
ans = ans[:ind]
dic = {a:i for i, a in enumerate(sorted(se))}
A = [dic[a] for a in A]
for q in query:
if q[0] == 1:
q[2] = dic[q[2]]
m = len(se)
itr = 12
for _ in range(itr):
P = random.choices(range(4), k=m)
bit = Bit(n)
B = A[:]
for i, a in enumerate(A):
add = 0
if P[a] & 1:
add |= 1
if P[a] & 2:
add |= 1 << 30
if add != 0:
bit.add(i, add)
for q in query:
if q[0] == 1:
i, x = q[1:]
b = B[i]
B[i] = x
add = 0
if P[b] & 1:
add -= 1
if P[b] & 2:
add -= 1 << 30
if P[x] & 1:
add += 1
if P[x] & 2:
add += 1 << 30
if add != 0:
bit.add(i, add)
else:
l, r, k, i = q[1:]
if ans[i] == "NO":
{{completion}}
c = bit.range_sum(l - 1, r)
if c % k != 0:
ans[i] = "NO"
elif (c >> 30) % k != 0:
ans[i] = "NO"
print(*ans, sep="\n")
T = 1
# T = int(input())
for t in range(1, T + 1):
solve()
|
continue
|
[{"input": "10 8\n1234 2 3 3 2 1 1 2 3 4\n2 1 6 2\n1 1 1\n2 1 6 2\n2 1 9 2\n1 10 5\n2 1 9 3\n1 3 5\n2 3 10 2", "output": ["NO\nYES\nNO\nYES\nYES"]}]
|
block_completion_007030
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: My orzlers, we can optimize this problem from $$$O(S^3)$$$ to $$$O\left(T^\frac{5}{9}\right)$$$!— Spyofgame, founder of Orzlim religionA long time ago, Spyofgame invented the famous array $$$a$$$ ($$$1$$$-indexed) of length $$$n$$$ that contains information about the world and life. After that, he decided to convert it into the matrix $$$b$$$ ($$$0$$$-indexed) of size $$$(n + 1) \times (n + 1)$$$ which contains information about the world, life and beyond.Spyofgame converted $$$a$$$ into $$$b$$$ with the following rules. $$$b_{i,0} = 0$$$ if $$$0 \leq i \leq n$$$; $$$b_{0,i} = a_{i}$$$ if $$$1 \leq i \leq n$$$; $$$b_{i,j} = b_{i,j-1} \oplus b_{i-1,j}$$$ if $$$1 \leq i, j \leq n$$$. Here $$$\oplus$$$ denotes the bitwise XOR operation.Today, archaeologists have discovered the famous matrix $$$b$$$. However, many elements of the matrix has been lost. They only know the values of $$$b_{i,n}$$$ for $$$1 \leq i \leq n$$$ (note that these are some elements of the last column, not the last row).The archaeologists want to know what a possible array of $$$a$$$ is. Can you help them reconstruct any array that could be $$$a$$$?
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$b_{1,n}, b_{2,n}, \ldots, b_{n,n}$$$ ($$$0 \leq b_{i,n} < 2^{30}$$$).
Output Specification: If some array $$$a$$$ is consistent with the information, print a line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. If there are multiple solutions, output any. If such an array does not exist, output $$$-1$$$ instead.
Notes: NoteIf we let $$$a = [1,2,3]$$$, then $$$b$$$ will be: $$$\bf{0}$$$$$$\bf{1}$$$$$$\bf{2}$$$$$$\bf{3}$$$$$$\bf{0}$$$$$$1$$$$$$3$$$$$$0$$$$$$\bf{0}$$$$$$1$$$$$$2$$$$$$2$$$$$$\bf{0}$$$$$$1$$$$$$3$$$$$$1$$$ The values of $$$b_{1,n}, b_{2,n}, \ldots, b_{n,n}$$$ generated are $$$[0,2,1]$$$ which is consistent with what the archaeologists have discovered.
Code:
a=[*map(int,[*open(0)][1].split())]
for k in 0,1:
for i in range(19):
z=1<<i
for j in range(len(a)):
if # TODO: Your code here:a[j-k*z]^=a[j+k*z-z]
print(*reversed(a))
|
a=[*map(int,[*open(0)][1].split())]
for k in 0,1:
for i in range(19):
z=1<<i
for j in range(len(a)):
if {{completion}}:a[j-k*z]^=a[j+k*z-z]
print(*reversed(a))
|
j&z
|
[{"input": "3\n0 2 1", "output": ["1 2 3"]}, {"input": "1\n199633", "output": ["199633"]}, {"input": "10\n346484077 532933626 858787727 369947090 299437981 416813461 865836801 141384800 157794568 691345607", "output": ["725081944 922153789 481174947 427448285 516570428 509717938 855104873 280317429 281091129 1050390365"]}]
|
control_completion_002076
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are $$$n$$$ students in the class, and you are given an array $$$s$$$ in non-decreasing order, where $$$s_i$$$ is the shoe size of the $$$i$$$-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation $$$p$$$ of $$$\{1,2,\ldots,n\}$$$ denoting a valid shuffling of shoes, where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student ($$$p_i \ne i$$$). And output $$$-1$$$ if a valid shuffling does not exist.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).
Input Specification: Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq10^5$$$) — the number of students. The second line of each test case contains $$$n$$$ integers $$$s_1, s_2,\ldots,s_n$$$ ($$$1\leq s_i\leq10^9$$$, and for all $$$1\le i<n$$$, $$$s_i\le s_{i+1}$$$) — the shoe sizes of the students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each test case, print the answer in a single line using the following format. If a valid shuffling does not exist, print the number $$$-1$$$ as the answer. If a valid shuffling exists, print $$$n$$$ space-separated integers — a permutation $$$p$$$ of $$$1,2,\ldots,n$$$ denoting a valid shuffling of shoes where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student. If there are multiple answers, then print any of them.
Notes: NoteIn the first test case, any permutation $$$p$$$ of $$$1,\ldots,n$$$ where $$$p_i\ne i$$$ would represent a valid shuffling since all students have equal shoe sizes, and thus anyone can wear anyone's shoes.In the second test case, it can be shown that no valid shuffling is possible.
Code:
import sys
input=sys.stdin.readline
for _ in range(int(input())):
n=int(input())
x=tuple(map(int,input().split()))
if n==1:
print(-1)
continue
ans=[-1]*n
extra=[]
visited=[False]*n
for i in range(n-1,-1,-1):
if i!=0 and x[i]==x[i-1]:
ans[i]=i
visited[i-1]=True
if not visited[i]:
extra.append(i+1)
else:
if extra:
ans[i]=extra.pop()
else:
# TODO: Your code here
else:
print(*ans)
|
import sys
input=sys.stdin.readline
for _ in range(int(input())):
n=int(input())
x=tuple(map(int,input().split()))
if n==1:
print(-1)
continue
ans=[-1]*n
extra=[]
visited=[False]*n
for i in range(n-1,-1,-1):
if i!=0 and x[i]==x[i-1]:
ans[i]=i
visited[i-1]=True
if not visited[i]:
extra.append(i+1)
else:
if extra:
ans[i]=extra.pop()
else:
{{completion}}
else:
print(*ans)
|
print(-1)
break
|
[{"input": "2\n5\n1 1 1 1 1\n6\n3 6 8 13 15 21", "output": ["5 1 2 3 4 \n-1"]}]
|
block_completion_002401
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Recently in Divanovo, a huge river locks system was built. There are now $$$n$$$ locks, the $$$i$$$-th of them has the volume of $$$v_i$$$ liters, so that it can contain any amount of water between $$$0$$$ and $$$v_i$$$ liters. Each lock has a pipe attached to it. When the pipe is open, $$$1$$$ liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $$$i$$$ to the lock $$$i + 1$$$. If the lock $$$i + 1$$$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $$$5$$$ locks with two open pipes at locks $$$1$$$ and $$$3$$$. Because locks $$$1$$$, $$$3$$$, and $$$4$$$ are already filled, effectively the water goes to locks $$$2$$$ and $$$5$$$. Note that the volume of the $$$i$$$-th lock may be greater than the volume of the $$$i + 1$$$-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $$$q$$$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $$$j$$$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $$$t_j$$$ seconds.Please help the mayor to solve this tricky problem and answer his queries.
Input Specification: The first lines contains one integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of locks. The second lines contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$1 \le v_i \le 10^9$$$)) — volumes of the locks. The third line contains one integer $$$q$$$ ($$$1 \le q \le 200\,000$$$) — the number of queries. Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \le t_j \le 10^9$$$) — the number of seconds you have to fill all the locks in the query $$$j$$$.
Output Specification: Print $$$q$$$ integers. The $$$j$$$-th of them should be equal to the minimum number of pipes to turn on so that after $$$t_j$$$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $$$-1$$$.
Notes: NoteThere are $$$6$$$ queries in the first example test. In the queries $$$1, 3, 4$$$ the answer is $$$-1$$$. We need to wait $$$4$$$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$. After $$$4$$$ seconds the locks $$$1$$$ and $$$4$$$ are full. In the following $$$1$$$ second $$$1$$$ liter of water is transferred to the locks $$$2$$$ and $$$5$$$. The lock $$$3$$$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$.In the fifth query one can open pipes $$$1, 2, 3, 4$$$.
Code:
n = int(input())
a = list(map(int, input().split()))
maxi = tot = 0
for i, j in enumerate(a, 1):
tot += j
maxi = max(maxi, (tot+i-1) // i)
q = int(input())
for _ in range(q):
k = int(input())
if # TODO: Your code here:
print(-1)
else:
# open x pipe
# time = ceil(sum / x) => x increased => time decrease
# => sum <= x * time -> x >= sum / time -> x = ceil(sum / time) (looking for x min)
print((tot + k - 1) // k)
|
n = int(input())
a = list(map(int, input().split()))
maxi = tot = 0
for i, j in enumerate(a, 1):
tot += j
maxi = max(maxi, (tot+i-1) // i)
q = int(input())
for _ in range(q):
k = int(input())
if {{completion}}:
print(-1)
else:
# open x pipe
# time = ceil(sum / x) => x increased => time decrease
# => sum <= x * time -> x >= sum / time -> x = ceil(sum / time) (looking for x min)
print((tot + k - 1) // k)
|
k < maxi
|
[{"input": "5\n4 1 5 4 1\n6\n1\n6\n2\n3\n4\n5", "output": ["-1\n3\n-1\n-1\n4\n3"]}, {"input": "5\n4 4 4 4 4\n6\n1\n3\n6\n5\n2\n4", "output": ["-1\n-1\n4\n4\n-1\n5"]}]
|
control_completion_004181
|
control_fixed
|
python
|
Complete the code in python to solve this programming problem:
Description: There are $$$n$$$ candies put from left to right on a table. The candies are numbered from left to right. The $$$i$$$-th candy has weight $$$w_i$$$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row). Of course, if Alice ate a candy, Bob can't eat it (and vice versa).They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the number of candies on the table. The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \leq w_i \leq 10^4$$$) — the weights of candies from left to right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
Output Specification: For each test case, print a single integer — the maximum number of candies Alice and Bob can eat in total while satisfying the condition.
Notes: NoteFor the first test case, Alice will eat one candy from the left and Bob will eat one candy from the right. There is no better way for them to eat the same total amount of weight. The answer is $$$2$$$ because they eat two candies in total.For the second test case, Alice will eat the first three candies from the left (with total weight $$$7$$$) and Bob will eat the first three candies from the right (with total weight $$$7$$$). They cannot eat more candies since all the candies have been eaten, so the answer is $$$6$$$ (because they eat six candies in total).For the third test case, there is no way Alice and Bob will eat the same non-zero weight so the answer is $$$0$$$.For the fourth test case, Alice will eat candies with weights $$$[7, 3, 20]$$$ and Bob will eat candies with weights $$$[10, 8, 11, 1]$$$, they each eat $$$30$$$ weight. There is no better partition so the answer is $$$7$$$.
Code:
for _ in range(int(input())):
n = int(input())
a = [*map(int, input().split())]
x = sum(a) // 2
s, d = 0, {}
for idx, i in enumerate(a):
s += i
if s > x: break
d[s] = idx + 1
s, r = 0, 0
for idx, i in enumerate(a[::-1]):
s += i
if # TODO: Your code here: r = idx + 1 + d[s]
print(r)
|
for _ in range(int(input())):
n = int(input())
a = [*map(int, input().split())]
x = sum(a) // 2
s, d = 0, {}
for idx, i in enumerate(a):
s += i
if s > x: break
d[s] = idx + 1
s, r = 0, 0
for idx, i in enumerate(a[::-1]):
s += i
if {{completion}}: r = idx + 1 + d[s]
print(r)
|
s in d
|
[{"input": "4\n3\n10 20 10\n6\n2 1 4 2 4 1\n5\n1 2 4 8 16\n9\n7 3 20 5 15 1 11 8 10", "output": ["2\n6\n0\n7"]}]
|
control_completion_000791
|
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 s[j^1][i]=='1':
# TODO: Your code here
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 s[j^1][i]=='1':
{{completion}}
print(max(f[n][0],f[n][1]))
|
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]))
|
[{"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"]}]
|
block_completion_008393
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: My orzlers, we can optimize this problem from $$$O(S^3)$$$ to $$$O\left(T^\frac{5}{9}\right)$$$!— Spyofgame, founder of Orzlim religionA long time ago, Spyofgame invented the famous array $$$a$$$ ($$$1$$$-indexed) of length $$$n$$$ that contains information about the world and life. After that, he decided to convert it into the matrix $$$b$$$ ($$$0$$$-indexed) of size $$$(n + 1) \times (n + 1)$$$ which contains information about the world, life and beyond.Spyofgame converted $$$a$$$ into $$$b$$$ with the following rules. $$$b_{i,0} = 0$$$ if $$$0 \leq i \leq n$$$; $$$b_{0,i} = a_{i}$$$ if $$$1 \leq i \leq n$$$; $$$b_{i,j} = b_{i,j-1} \oplus b_{i-1,j}$$$ if $$$1 \leq i, j \leq n$$$. Here $$$\oplus$$$ denotes the bitwise XOR operation.Today, archaeologists have discovered the famous matrix $$$b$$$. However, many elements of the matrix has been lost. They only know the values of $$$b_{i,n}$$$ for $$$1 \leq i \leq n$$$ (note that these are some elements of the last column, not the last row).The archaeologists want to know what a possible array of $$$a$$$ is. Can you help them reconstruct any array that could be $$$a$$$?
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$b_{1,n}, b_{2,n}, \ldots, b_{n,n}$$$ ($$$0 \leq b_{i,n} < 2^{30}$$$).
Output Specification: If some array $$$a$$$ is consistent with the information, print a line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. If there are multiple solutions, output any. If such an array does not exist, output $$$-1$$$ instead.
Notes: NoteIf we let $$$a = [1,2,3]$$$, then $$$b$$$ will be: $$$\bf{0}$$$$$$\bf{1}$$$$$$\bf{2}$$$$$$\bf{3}$$$$$$\bf{0}$$$$$$1$$$$$$3$$$$$$0$$$$$$\bf{0}$$$$$$1$$$$$$2$$$$$$2$$$$$$\bf{0}$$$$$$1$$$$$$3$$$$$$1$$$ The values of $$$b_{1,n}, b_{2,n}, \ldots, b_{n,n}$$$ generated are $$$[0,2,1]$$$ which is consistent with what the archaeologists have discovered.
Code:
a=[*map(int,[*open(0)][1].split())]
for k in 0,1:
for i in range(19):
z=1<<i
for j in range(len(a)):
if j&z:# TODO: Your code here
print(*reversed(a))
|
a=[*map(int,[*open(0)][1].split())]
for k in 0,1:
for i in range(19):
z=1<<i
for j in range(len(a)):
if j&z:{{completion}}
print(*reversed(a))
|
a[j-k*z]^=a[j+k*z-z]
|
[{"input": "3\n0 2 1", "output": ["1 2 3"]}, {"input": "1\n199633", "output": ["199633"]}, {"input": "10\n346484077 532933626 858787727 369947090 299437981 416813461 865836801 141384800 157794568 691345607", "output": ["725081944 922153789 481174947 427448285 516570428 509717938 855104873 280317429 281091129 1050390365"]}]
|
block_completion_002116
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given a positive integer $$$n$$$. Let's call some positive integer $$$a$$$ without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express $$$n$$$ as a sum of positive palindromic integers. Two ways are considered different if the frequency of at least one palindromic integer is different in them. For example, $$$5=4+1$$$ and $$$5=3+1+1$$$ are considered different but $$$5=3+1+1$$$ and $$$5=1+3+1$$$ are considered the same. Formally, you need to find the number of distinct multisets of positive palindromic integers the sum of which is equal to $$$n$$$.Since the answer can be quite large, print it modulo $$$10^9+7$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$) denoting the number of testcases. Each testcase contains a single line of input containing a single integer $$$n$$$ ($$$1\leq n\leq 4\cdot 10^4$$$) — the required sum of palindromic integers.
Output Specification: For each testcase, print a single integer denoting the required answer modulo $$$10^9+7$$$.
Notes: NoteFor the first testcase, there are $$$7$$$ ways to partition $$$5$$$ as a sum of positive palindromic integers: $$$5=1+1+1+1+1$$$ $$$5=1+1+1+2$$$ $$$5=1+2+2$$$ $$$5=1+1+3$$$ $$$5=2+3$$$ $$$5=1+4$$$ $$$5=5$$$ For the second testcase, there are total $$$77$$$ ways to partition $$$12$$$ as a sum of positive integers but among them, the partitions $$$12=2+10$$$, $$$12=1+1+10$$$ and $$$12=12$$$ are not valid partitions of $$$12$$$ as a sum of positive palindromic integers because $$$10$$$ and $$$12$$$ are not palindromic. So, there are $$$74$$$ ways to partition $$$12$$$ as a sum of positive palindromic integers.
Code:
import sys
input = sys.stdin.readline
s = []
c = [1]
for y in range(1,40005):
if str(y) == (str(y))[::-1]:
s.append(y)
c.append(0)
for i in s:
for j in range(1,40005):
if # TODO: Your code here:
c[j] += (c[j - i]) % ((10 ** 9) + 7)
a = int(input())
for y in range(a):
b = int(input())
print(c[b] % ((10 ** 9) + 7))
|
import sys
input = sys.stdin.readline
s = []
c = [1]
for y in range(1,40005):
if str(y) == (str(y))[::-1]:
s.append(y)
c.append(0)
for i in s:
for j in range(1,40005):
if {{completion}}:
c[j] += (c[j - i]) % ((10 ** 9) + 7)
a = int(input())
for y in range(a):
b = int(input())
print(c[b] % ((10 ** 9) + 7))
|
j >= i
|
[{"input": "2\n5\n12", "output": ["7\n74"]}]
|
control_completion_004692
|
control_fixed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.