text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, β¦, p_n) is a permutation (p_i, p_{i + 1}, β¦, p_{n}, p_1, p_2, β¦, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, β¦, a_{i_k} for some i_1, i_2, β¦, i_k such that l β€ i_1 < i_2 < β¦ < i_k β€ r.
Input
The first line contains three integers n, m, q (1 β€ n, m, q β€ 2 β
10^5) β the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Submitted Solution:
```
import os
from io import BytesIO, StringIO
#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main():
n, m, q = map(int, input().split())
p = list(map(int, input().split()))
a = list(map(int, input().split()))
if n == 1:
print('1'*q)
return
next_p = [0] * n
next_a = [0] * m
prev = p[-1] - 1
for pi in p:
pi -= 1
next_p[prev] = pi
prev = pi
idx_a = [0] * n
for i in range(len(a)-1, -1, -1):
ai = a[i] - 1
next_a[i] = idx_a[next_p[ai]]
idx_a[ai] = i
ep = [0] * m
for c in range(0, m - n + 1):
origc = c
flag = True
for _ in range(n-1):
if next_a[c] != 0:
c = next_a[c]
else:
flag = False
break
if flag:
ep[origc] = c
mn = 200000
for i in range(len(ep)-1, -1, -1):
epi = ep[i]
if epi != 0:
if epi > mn:
ep[i] = mn
mn = min(mn, epi)
out = []
for _ in range(q):
l, r = map(int, input().split())
l, r = l-1, r-1
if ep[l] == 0 or ep[l] > r:
out.append('0')
else:
out.append('1')
print(''.join(out))
main()
```
No
| 97,000 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, β¦, p_n) is a permutation (p_i, p_{i + 1}, β¦, p_{n}, p_1, p_2, β¦, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, β¦, a_{i_k} for some i_1, i_2, β¦, i_k such that l β€ i_1 < i_2 < β¦ < i_k β€ r.
Input
The first line contains three integers n, m, q (1 β€ n, m, q β€ 2 β
10^5) β the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Submitted Solution:
```
import sys
class segmentTree:
def __init__(self, n):
self.n = n
self.seg = [self.n + 1] * (self.n << 1)
def update(self, p, value):
p += self.n
self.seg[p] = value
while p > 1:
p >>= 1
self.seg[p] = min(self.seg[p * 2], self.seg[p * 2 + 1])
def query(self, l, r):
res = self.n
l += self.n
r += self.n
while l < r:
if l & 1:
res = min(res, self.seg[l])
l += 1
if r & 1:
res = min(res, self.seg[r - 1])
r -= 1
l >>= 1
r >>= 1
return res
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
if n == 1:
print('1' * q)
exit(0)
elif m < n:
print('0' * q)
exit(0)
else:
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
rightmost_pos = [-1] * (n + 1)
left_neighbor = [-1] * m
for i in range(m):
index = index_arr[a[i]]
left_index = n - 1 if index == 0 else index - 1
left = p[left_index]
left_neighbor[i] = rightmost_pos[left]
rightmost_pos[a[i]] = i
leftmost_pos = [-1] * (n + 1)
last = [-1] * m
cnt = [1] * m
for i in range(m - 1, -1, -1):
index = index_arr[a[i]]
right_index = 0 if index == n - 1 else index + 1
right = p[right_index]
last[i] = i
if leftmost_pos[right] != -1:
cnt[i] += cnt[leftmost_pos[right]]
last[i] = last[leftmost_pos[right]]
cnt[i] = min(n + 1, cnt[i])
if cnt[i] > n:
last[i] = left_neighbor[last[i]]
leftmost_pos[a[i]] = i
#tree = segmentTree(m)
#for i in range(m):
# if cnt[i] >= n:
# tree.update(i, last[i])
# else:
# tree.update(i, m)
inp_idx = n + m + 3
ans = ''
for i in range(q):
l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
#bestR = tree.query(l, r + 1)
if last[l] <= r:
ans += '1'
else:
ans += '0'
print(ans)
```
No
| 97,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, β¦, p_n) is a permutation (p_i, p_{i + 1}, β¦, p_{n}, p_1, p_2, β¦, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, β¦, a_{i_k} for some i_1, i_2, β¦, i_k such that l β€ i_1 < i_2 < β¦ < i_k β€ r.
Input
The first line contains three integers n, m, q (1 β€ n, m, q β€ 2 β
10^5) β the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Submitted Solution:
```
import sys
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
# if n == 1:
# print('1' * q)
# exit(0)
# elif m < n:
# print('0' * q)
# exit(0)
# else:
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
leftmost_pos = [m] * (n + 1)
next = [-1] * m
for i in range(m - 1, -1, -1):
index = index_arr[a[i]]
right_index = 0 if index == n - 1 else index + 1
right = p[right_index]
next[i] = leftmost_pos[right]
leftmost_pos[a[i]] = i
log = 0
while (1 << log) <= n: log += 1
dp = [[m for _ in range(m + 1)] for _ in range(log)]
for i in range(m):
dp[0][i] = next[i]
for j in range(1, log):
for i in range(m):
dp[j][i] = dp[j - 1][dp[j - 1][i]]
last = [m] * m
for i in range(m):
p = i
len = n - 1
for j in range(log - 1, -1, -1):
if (1 << j) <= len:
p = dp[j][p]
len -= (1 << j)
last[i] = p
inp_idx = n + m + 3
ans = ''
for i in range(q):
l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
if last[l] <= r:
ans += '1'
else:
ans += '0'
print(ans)
```
No
| 97,002 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, β¦, p_n) is a permutation (p_i, p_{i + 1}, β¦, p_{n}, p_1, p_2, β¦, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, β¦, a_{i_k} for some i_1, i_2, β¦, i_k such that l β€ i_1 < i_2 < β¦ < i_k β€ r.
Input
The first line contains three integers n, m, q (1 β€ n, m, q β€ 2 β
10^5) β the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Submitted Solution:
```
import sys
class segmentTree:
def __init__(self, n):
self.n = n
self.seg = [self.n] * (self.n << 1)
def update(self, p, value):
p += self.n
self.seg[p] = value # l and r - 1 should be the same
while p > 1:
p >>= 1
self.seg[p] = min(self.seg[p * 2], self.seg[p * 2 + 1])
def query(self, l, r):
res = self.n
l += self.n
r += self.n
while l < r:
if l & 1:
res = min(res, self.seg[l])
l += 1
if r & 1:
res = min(res, self.seg[r - 1])
r -= 1
l >>= 1
r >>= 1
return res
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
if n == 1:
print('1' * q)
exit(0)
elif m < n:
print('0' * q)
exit(0)
else:
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
rightmost_pos = [-1] * (n + 1)
left_neighbor = [-1] * m
for i in range(m):
index = index_arr[a[i]]
left_index = n - 1 if index == 0 else index - 1
left = p[left_index]
left_neighbor[i] = rightmost_pos[left]
rightmost_pos[a[i]] = i
last = [-1] * m
cnt = [1] * m
leftmost_pos = [-1] * m
for i in range(m - 1, -1, -1):
index = index_arr[a[i]]
right_index = 0 if index == n - 1 else index + 1
right = p[right_index]
last[i] = i
if leftmost_pos[right] != -1:
cnt[i] += cnt[leftmost_pos[right]]
last[i] = last[leftmost_pos[right]]
if cnt[i] > n:
last[i] = left_neighbor[last[i]]
leftmost_pos[a[i]] = i
tree = segmentTree(m)
for i in range(m):
if cnt[i] >= n:
tree.update(i, last[i])
else:
tree.update(i, m)
inp_idx = n + m + 3
ans = ''
for i in range(q):
l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
bestR = tree.query(l, r)
if bestR <= r:
ans += '1'
else:
ans += '0'
print(ans)
```
No
| 97,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
if __name__ == '__main__':
cin = lambda: [*map(int, input().split())] #δΈθ‘δΈθ‘θ―»
n, m = cin()
se = set()
x = [tuple(sorted(cin())) for _ in range(m)]
for e in x:
se.add((e[0] - 1, e[1] - 1))
for i in range(1, n):
if n % i != 0:
continue
ok = True
for e in se:
if tuple(sorted([(e[0] + i) % n, (e[1] + i) % n])) not in se:
# print(i, e, tuple([(e[0] + i) % n, (e[1] + i) % n]))
ok = False
break
if ok:
print('Yes')
exit(0)
print('No')
```
| 97,004 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
"""
Satwik_Tiwari ;) .
30th july , 2020 - Thursday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
ans = 1
while(b>0):
if(b%2==1):
ans*=a
a*=a
b//=2
return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def solve():
n,m = sep()
div =[]
for i in range(1,floor(n**(0.5))+1):
if(n%i==0):
div.append(i)
if((n//i)!=n and (n//i)!=i):
div.append(n//i)
graph = set()
for i in range(m):
a,b=sep()
a-=1
b-=1
a,b = min(a,b),max(a,b)
graph.add((a,b))
for i in range(len(div)):
f = True
for j in graph:
a,b = (j[0]+div[i])%n , (j[1]+div[i])%n
a,b = min(a,b),max(a,b)
if((a,b) not in graph):
f = False
break
if(f):
print('Yes')
return
print('No')
testcase(1)
# testcase(int(inp()))
```
| 97,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
nz = [int(x) for x in input().split()]
edges = set()
divisors = set()
for x in range (0,nz[1]):
uv = [ y for y in input().split()]
edges.add(uv[0] + ' ' + uv[1])
for x in range(1,nz[0]):
if nz[0] % x == 0:
divisors.add(x)
flag = 0
for y in divisors:
flag = 0
for x in edges:
u = (int(x.split()[0]) + y) % nz[0]
v = (int(x.split()[1]) + y) % nz[0]
if u == 0:
u = nz[0]
if v == 0:
v = nz[0]
if str(u) + ' ' + str(v) not in edges:
if str(v) + ' ' + str(u) not in edges:
flag = 1
break
if flag == 0:
print("Yes")
break
if flag == 1:
print("No")
```
| 97,006 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
def gcd(x,y):
while y:
x,y = y,x%y
return x
def lcm(a,b): return (a*b)//gcd(a,b)
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
kk=lambda:map(int,input().split())
k2=lambda:map(lambda x:int(x)-1, input().split())
ll=lambda:list(kk())
n,m=kk()
nodes = [[] for _ in range(n)]
for _ in range(m):
n1,n2=k2()
nodes[n1].append((n2-n1)%n)
nodes[n2].append((n1-n2)%n)
seen = {}
nextv=0
lists = []
node2,used = [0]*n, [False]*n
for i,no in enumerate(nodes):
t = tuple(sorted(no))
if not t in seen:
seen[t],nextv = nextv,nextv+1
lists.append([])
lists[seen[t]].append(i)
node2[i] = seen[t]
lists.sort(key=len)
valids = set()
for i in range(nextv-1):
cl = lists[i]
n0 = cl[0]
continueing = True
while continueing:
continueing = False
for j in range(1,len(cl)):
if used[cl[j]]: continue
dist = cl[j]-n0
if n%dist != 0: continue
for k in range(n0, n+n0, dist):
k = k%n
if used[k] or node2[k] != node2[n0]:
break
else:
# we found a working one.
valids.add(dist)
for k in range(n0, n+n0, dist):
k = k%n
used[k]=True
cl = [x for x in cl if (x-n0)%dist != 0]
n0 = cl[0] if cl else 0
continueing= True
break
if len(cl) > 0:
print("NO")
exit()
lc =1
for value in valids:
lc = lcm(lc, value)
print("YES" if lc< n else "NO")
```
| 97,007 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
import sys
import collections
# see tutorial at https://codeforces.com/blog/entry/66878
n, m = map(int, input().split())
# segment length -> start
segs = set()
for _ in range(m):
start, end = map(int, input().split())
segs.add((start-1, end-1))
def get_divisors(n):
"""
:param n:
:return: divisors of n excluding n itself
"""
divisors = []
for i in range(1, n):
if n % i == 0:
divisors.append(i)
return divisors
divisors = get_divisors(n)
# try out all divisors as the total (actual) rotation period, not just the rotation period for a subset of segments
for k in divisors:
for sega, segb in segs:
if ((sega + k) % n, (segb + k) % n) not in segs and ((segb + k) % n, (sega + k) % n) not in segs:
# this k doesn't work
break
else:
print('Yes')
sys.exit()
print('No')
```
| 97,008 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
import sys
def No():
print('No')
sys.exit()
def divi(n):
res = [1]
for i in range(2, int(n**0.5)+1):
if n % i == 0:
res.append(i)
if i != n // i:
res.append(n//i)
return res
N, M = map(int, input().split())
DN = divi(N)
dis = [set() for _ in range(N//2 + 1)]
for i in range(M):
a, b = map(lambda x:int(x) - 1, sys.stdin.readline().split())
fn, ln = (a - b)%N, (b - a)%N
if fn < ln:
dis[fn].add(b)
elif ln < fn:
dis[ln].add(a)
else:
dis[fn].add(a)
dis[fn].add(b)
for dn in DN:
for D in dis:
if not D:
continue
for d in D:
if (d+dn)%N not in D:
break
else:
continue
break
else:
print('Yes')
sys.exit()
No()
```
| 97,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def main():
n, m = map(int, input().split())
S = set()
for i in range(m):
a, b = map(int, input().split())
a, b = a-1, b-1
if a > b:
a, b = b, a
S.add((a, b))
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
#divisors.sort(reverse=True)
return divisors
D = make_divisors(n)
for d in D:
if d == n:
continue
T = set()
flag = True
for a, b in S:
na = (a+d)%n
nb = (b+d)%n
if na > nb:
na, nb = nb, na
if (na, nb) not in S:
flag = False
break
T.add((na, nb))
if not flag:
continue
for a, b in S:
if (a, b) not in T:
break
else:
print('Yes')
exit()
else:
print('No')
if __name__ == '__main__':
main()
```
| 97,010 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Tags: brute force, strings
Correct Solution:
```
n, m = map(int, input().split())
arr = [set() for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
f = b - a
if f < 0:
f += n
arr[a].add(f)
f = a - b
if f < 0:
f += n
arr[b].add(f)
lst = [1]
for i in range(2, int(n ** 0.5) + 1):
if (n % i == 0):
lst.append(i)
lst.append(n // i)
flag = 0
#print(lst)
for el in lst:
for i in range(n):
next = (i + el) % n
if arr[i] != arr[next]:
flag = 1
break
if flag == 0:
print("Yes")
# print(el)
exit(0)
flag = 0
print("No")
```
| 97,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
n, m = map(int, input().split())
a = []
for i in range(m):
a.append(list(map(int, input().split())))
if (a[i][0] > a[i][1]):
a[i][0], a[i][1] = a[i][1], a[i][0]
if (a[i][1] - a[i][0] > n / 2):
a[i][0] += n
a[i][0], a[i][1] = a[i][1], a[i][0]
if (m == 1):
if (a[0][1] - a[0][i] == n / 2):
print("Yes")
else:
print("No")
exit(0)
a.sort()
for i in range(m):
a.append([a[i][0] + n, a[i][1] + n])
b = []
for i in range(2 * m - 1):
if (a[i][1] - a[i][0] == n / 2):
b.append((a[i][1] - a[i][0], min(a[i + 1][0] - a[i][0], n - a[i + 1][0] + a[i][0])))
else:
b.append((a[i][1] - a[i][0], a[i + 1][0] - a[i][0]))
# Z function
z = [0] * 2 * m
l = r = 0
for i in range(1, m):
if (i <= r):
z[i] = min(z[i - l], r - i + 1)
while (i + z[i] < len(b) and b[i + z[i]] == b[z[i]]):
z[i] += 1
if (i + z[i] - 1 > r):
l = i
r = i + z[i] - 1
if (z[i] >= m):
print("Yes")
exit(0)
print("No")
```
Yes
| 97,012 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
from math import gcd
def primes():
yield 2; yield 3; yield 5; yield 7;
bps = (p for p in primes()) # separate supply of "base" primes (b.p.)
p = next(bps) and next(bps) # discard 2, then get 3
q = p * p # 9 - square of next base prime to keep track of,
sieve = {} # in the sieve dict
n = 9 # n is the next candidate number
while True:
if n not in sieve: # n is not a multiple of any of base primes,
if n < q: # below next base prime's square, so
yield n # n is prime
else:
p2 = p + p # n == p * p: for prime p, add p * p + 2 * p
sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step
p = next(bps); q = p * p # pull next base prime, and get its square
else:
s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple
while nxt in sieve: nxt += s # ensure each entry is unique
sieve[nxt] = s # nxt is next non-marked multiple of this prime
n += 2 # work on odds only
import itertools
def get_prime_divisors(limit):
return list(itertools.filterfalse(lambda p: limit % p, itertools.takewhile(lambda p: p <= limit, primes())))
n, m = map(int, input().split())
data = {}
for _ in range(m):
a, b = map(int, input().split())
a, b = min(a, b)-1, max(a, b)-1
x, y = b-a, n-b+a
if x <= y:
if x in data:
data[x].add(a)
else:
data[x] = set([a])
if y <= x:
if y in data:
data[y].add(b)
else:
data[y] = set([b])
t = n
for s in data.values():
t = gcd(t, len(s))
if t == 1:
print("No")
else:
tests = get_prime_divisors(t)
for k in tests:
d = n//k
for s in data.values():
if any(map(lambda v: (v+d)%n not in s, s)):
break
else:
print("Yes")
break
else:
print("No")
```
Yes
| 97,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
def divs(n):
res = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
res.append(i)
res.append(n // i)
if int(n ** 0.5) ** 2 == n:
res.pop()
return res
def main():
n, m = map(int, input().split())
angles = [set() for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
a1 = b - a
if a1 < 0:
a1 += n
angles[a].add(a1)
b1 = a - b
if b1 < 0:
b1 += n
angles[b].add(b1)
d = divs(n)
for di in d:
if di == n:
continue
flag = 1
for i in range(n):
if angles[i] != angles[(i + di) % n]:
flag = 0
break
if flag == 1:
print("Yes")
return 0
print("No")
return 0
main()
```
Yes
| 97,014 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
(n,m) = [int(x) for x in input().split()]
segs =set()
for i in range(m):
segs.add(tuple(sorted((int(x)-1 for x in input().split()))))
for i in range(1,n):
if n%i!=0:
continue
j=0
for a,b in segs:
if tuple(sorted(((a+i)%n,(b+i)%n))) not in segs:
break
j+=1
if j==m:
print("Yes")
exit()
print("No")
```
Yes
| 97,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
from math import gcd
def primes():
yield 2; yield 3; yield 5; yield 7;
bps = (p for p in primes()) # separate supply of "base" primes (b.p.)
p = next(bps) and next(bps) # discard 2, then get 3
q = p * p # 9 - square of next base prime to keep track of,
sieve = {} # in the sieve dict
n = 9 # n is the next candidate number
while True:
if n not in sieve: # n is not a multiple of any of base primes,
if n < q: # below next base prime's square, so
yield n # n is prime
else:
p2 = p + p # n == p * p: for prime p, add p * p + 2 * p
sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step
p = next(bps); q = p * p # pull next base prime, and get its square
else:
s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple
while nxt in sieve: nxt += s # ensure each entry is unique
sieve[nxt] = s # nxt is next non-marked multiple of this prime
n += 2 # work on odds only
import itertools
def get_prime_divisors(limit):
return list(itertools.filterfalse(lambda p: limit % p, itertools.takewhile(lambda p: p <= limit, primes())))
n, m = map(int, input().split())
data = {}
for _ in range(m):
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
x, y = b-a, n-b+a
if x <= y:
if x in data:
data[x].add(a)
else:
data[x] = set([a])
if y <= x:
if y in data:
data[y].add(b)
else:
data[y] = set([b])
t = n
for s in data.values():
t = gcd(t, len(s))
if t == 1:
print("No")
else:
tests = get_prime_divisors(t)
for k in tests:
d = n//k
for s in data.values():
if any(map(lambda v: (v+d)%n not in s, s)):
break
else:
print("Yes")
break
else:
print("No")
```
No
| 97,016 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
import sys
import collections
n, m = map(int, input().split())
# segment length -> start
len2start = collections.defaultdict(set)
for _ in range(m):
start, end = map(int, input().split())
len2start[(end - start) % n].update([start - 1, end - 1])
def get_divisors(n):
"""
:param n:
:return: divisors of n excluding n itself
"""
divisors = []
for i in range(1, n):
if n % i == 0:
divisors.append(i)
return divisors
divisors = get_divisors(n)
for length, segs in len2start.items():
# try out all divisors
for k in divisors:
if len(segs) == 0:
break
for phase in range(k):
for p in range(n // k):
if (phase + k*p) % n not in segs:
break
else:
# if this k, phase and p work, delete the corresponding numbers
for p in range(n // k):
segs.remove((phase + k*p) % n)
if len(segs) > 0:
print('No')
sys.exit()
print('Yes')
```
No
| 97,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
import sys
def No():
print('No')
sys.exit()
def divi(n):
res = [1]
for i in range(2, int(n**0.5)+1):
if n % i == 0:
res.append(i)
if i != n // i:
res.append(n//i)
return res
N, M = map(int, input().split())
DN = divi(N)
dis = [set() for _ in range(N//2 + 1)]
for i in range(M):
a, b = map(int, sys.stdin.readline().split())
fn, ln = (a - b)%N, (b - a)%N
if fn < ln:
dis[fn].add(b)
elif ln < fn:
dis[ln].add(a)
else:
dis[fn].add(a)
dis[fn].add(b)
for dn in DN:
for D in dis:
if not D:
continue
for d in D:
if (d+dn)%N not in D:
break
else:
continue
break
else:
print('Yes')
sys.exit()
No()
```
No
| 97,018 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 β€ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 β€ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 200 000) β the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line β "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
(n,m) = [int(x) for x in input().split()]
segs =[]
for i in range(m):
segs+=[[int(x) for x in input().split()]]
i=0
j=1
len = 1
while(j<m):
if abs(segs[j][1]-segs[j][0])==abs(segs[i][1]-segs[i][0]):
i+=1
j+=1
len = j-i
else:
if(i==0):
j+=1
else:
i=0
len=j+1
poss = "Yes"
if(len==m):
poss="No"
for i in range(0,m-2*len,len):
if(poss=="No"):
break
diff = abs(segs[i+len][0]-segs[i][0])
for j in range(i+len,i+len+len):
if(segs[i][0]+diff!=segs[j][0]):
poss="No"
break
print(poss)
```
No
| 97,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
for n in range(int(input())):
lvl,tot,a,b=map(int,input().split())
if tot*b>=lvl:
print(-1)
continue
hi=tot
lo=0
res=0
while hi>=lo:
justpl=(hi+lo)//2
u=justpl*a+(tot-justpl)*b
if justpl*a+(tot-justpl)*b<lvl:
lo=justpl+1
res=justpl
else:
hi=justpl-1
print(res)
```
| 97,020 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
for q in range(int(input())):
k,n,a,b=map(int,input().split(" "))
rem=k-n*b
if rem<=0:
print(-1)
else:
val=(rem-1)//(a-b)
if val>n:
print(n)
else:
print(val)
```
| 97,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
def f(ans, k, b, n, a):
works = True
r = k
if ans > n:
works = False
else:
if r > a * ans:
r -= a * ans
if not (((r - 1) // b) >= n - ans and r > b * (n - ans)):
works = False
else:
works = False
return works
def bS(l, r, k, b, n, a):
while True:
mid = (l + r) // 2
if r - l == 1:
break
if f(mid, k, b, n, a):
l = mid
else:
r = mid
if f(r, k, b, n, a):
return r
return l
def main():
for _ in range(int(input())):
k, n, a, b = map(int, input().split())
ans = bS(0, n + 3, k, b, n, a)
if f(ans, k, b, n, a):
print(ans)
else:
print(-1)
main()
```
| 97,022 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
#!/usr/bin/env python3
from sys import stdin
import math
def solve(tc):
k, n, a, b = map(int, stdin.readline().split())
if k<=b*n:
print(-1)
return
r = (k - (b * n)) // (a - b)
if (k-(b*n)) % (a-b) == 0:
r -= 1
print(min(r,n))
LOCAL_TEST = not __debug__
if LOCAL_TEST:
infile = __file__.split('.')[0] + "-test.in"
stdin = open(infile, 'r')
tcs = (int(stdin.readline().strip()))# if LOCAL_TEST else 1)
tc = 1
while tc <= tcs:
solve(tc)
tc += 1
```
| 97,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
for q in range(int(input())):
k, n, a, b = map(int, input().split())
if k <= n * b:
print(-1)
else:
l = 0
r = 10 ** 9
while l + 1 < r:
x = (l + r) // 2
if (k - x * a - 1) // b + x >= n:
l = x
else:
r = x
print(min(n, l))
```
| 97,024 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
k,n,a,b = list(map(int, input().split()))
s = b*n
if s >= k:
print(-1)
else:
print(min((k-s-1)//(a-b), n))
```
| 97,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
t=int(input(''))
for _ in range(t):
n,k,a,b=map(int, input().split())
if (k*a)<n:
print(k)
continue
elif n<= k*b:
print(-1)
continue
else:
a-=b
l=n-(b*k)
if l%a==0:
print((l//a)-1)
else:
print(l//a)
```
| 97,026 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Tags: binary search, math
Correct Solution:
```
#Anuneet Anand
q=int(input())
while q:
k,n,a,b=map(int,input().split())
c=0
if k-n*b<=0:
c=-1
elif k-n*a>0:
c=n
else:
c=(k-n*b)/(a-b)
if int(c)==c:
c=int(c)-1
else:
c=int(c)
print(c)
q=q-1
```
| 97,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
'''
from sys import stdin,stdout
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
arr = list(map(int, stdin.readline().split()))
d = {}
for i in arr:
if i in d:
d[i] += 1
else:
d[i] = 1
cnt = list(d[i] for i in d)
cnt.sort(reverse = True)
ans = []
ans.append(cnt[0])
for i in range(1, len(cnt)):
if cnt[i-1] != 0:
while cnt[i]>0:
if cnt[i] not in ans:
ans.append(cnt[i])
break
else:
cnt[i] -= 1
else:
break
stdout.write('{}\n'.format(sum(ans)))
'''
'''
a = int(input())
while True:
temp = a; s=0
while temp != 0:
s += temp%10
temp //= 10
if s%4 == 0:
break
a += 1
print(a)
'''
'''
for _ in range(int(input())):
n, k = map(int, input().split())
arr = list(map(int, input().split()))
if min(arr)+k < max(arr)-k:
print(-1)
else:
print(min(arr)+k)
'''
for _ in range(int(input())):
k, n, a, b = map(int, input().split())
ans = (b * n - k + 1) // (b - a)
print(min(n, ans) if ans >= 0 else -1)
```
Yes
| 97,028 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
def main():
def pos(x, a, b, k):
return ((a * x + b * (n - x)) < k)
for i in range(int(input())):
k, n, a, b = map(int, input().split())
left, right = -1, n + 1
while left + 1 < right:
mid = (left + right) // 2
if pos(mid, a, b, k):
left = mid
else:
right = mid
print(left)
main()
```
Yes
| 97,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
for _ in range(int(input())):
k,n,a,b = map(int,input().split())
if n*b>=k:
print(-1)
else:
num = k-(b*n)-1
deno = a-b
print(min(num//deno,n))
```
Yes
| 97,030 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
from math import *
p = int(input())
A = []
for i in range(p):
k, n, a, b = map(int, input().split())
x = (k - n*b)/(a - b)
x = ceil(x)-1
if x > n:
x = n
if x < 0:
x = -1
A.append(x)
for i in range(p):
print(A[i])
```
Yes
| 97,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
def ispossible(charge, playcost, lowplaycost, playcnt, allcnt):
return charge > playcost*playcnt + lowplaycost*(allcnt - playcnt)
def solution():
k, n, a, b = map(int, input().split())
if k <= b*n:
return -1
l = 0
r = n + 1
while r - l > 1:
m = (r+l)//2
if ispossible(k, a, b, m, n) == True:
l = m
else:
r = m
return l
def main():
test = int(input())
for i in range(test):
print(i,solution())
return
if __name__ == "__main__":
main()
```
No
| 97,032 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
t = int(input())
while t:
k, n, a, b = [int(a) for a in input().split(" ")]
p = (k - b * n) // (a - b)
diff = ((k - b * n) / (a - b)) - p
if p == 0 and diff == 0:
print('-1')
elif diff == 0:
print(max(min(p - 1, n), 0))
else:
print(max(min(p, n), 0))
t -= 1
```
No
| 97,033 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
import math
t=int(input())
for _ in range(t):
k,n,a,b,=map(int,input().split())
val=min(a,b)
if k-n*val>0:
if val==a:
print(n)
elif k-a*n>0:
print(n)
else:
f=1
for i in range(n-1,0,-1):
if i*a+(n-i)*b<=k:
print(i)
f=0
break
if f==1:
print(0)
else:
print(-1)
```
No
| 97,034 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^5) β the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 β€ k, n β€ 10^9, 1 β€ b < a β€ 10^9) β the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
Submitted Solution:
```
import math,bisect
from collections import Counter,defaultdict
I =lambda:int(input())
M =lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))
for _ in range(I()):
k,n,a,b=M()
if k//b<=n:
print(-1)
else:
ans=k//a;k-=ans*a
while ans+(k//b)<n:
ans-=1;k+=a
if ans==n and k%a==0:ans-=1
print(min(ans,n))
```
No
| 97,035 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
from sys import stdin
from sys import setrecursionlimit as SRL; SRL(10**7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())
n,k = rrd()
s = []
cal = [[0]*(n+10) for _i in range(n+10)]
for i in range(n):
s.append(str(rd()))
ans = 0
for i in range(n):
j = 0
while j < n and s[i][j] == 'W':
j += 1
l = j
if j >= n:
ans += 1
continue
j = n-1
while j >= 0 and s[i][j] == 'W':
j -= 1
r = j
if r - l + 1 > k:
continue
l1 = max(0,i - k + 1)
r1 = i + 1
l2 = max(0,r - k + 1)
r2 = l + 1
cal[l1][l2] += 1
cal[r1][l2] -= 1
cal[l1][r2] -= 1
cal[r1][r2] += 1
for i in range(n):
j = 0
while j < n and s[j][i] == 'W':
j += 1
l = j
if j >= n:
ans += 1
continue
j = n-1
while j >= 0 and s[j][i] == 'W':
j -= 1
r = j
if r-l+1 > k:
continue
l1 = max(0,i - k + 1)
r1 = i + 1
l2 = max(0,r - k + 1)
r2 = l + 1
cal[l2][l1] += 1
cal[l2][r1] -= 1
cal[r2][l1] -= 1
cal[r2][r1] += 1
for i in range(n):
for j in range(n):
if j:
cal[i][j] += cal[i][j-1]
pans = 0
for j in range(n):
for i in range(n):
if i:
cal[i][j] += cal[i-1][j]
pans = max(pans,cal[i][j])
print(ans+pans)
```
| 97,036 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
from sys import stdin, stdout
from collections import *
from array import *
def iarr(delim = " "): return map(int, input().split(delim))
def mat(n, m, v = None): return [[v]*m for _ in range(n)]
n, k, *_ = iarr()
lc = [-1]*n
rc = [n]*n
tr = [-1]*n
br = [n]*n
b = [input() for _ in range(n)]
ans = mat(n, n, 0)
pre, post = 0, 0
for i, r in enumerate(b):
for j, c in enumerate(r):
if c == 'B':
rc[i], br[j] = j, i
if lc[i] == -1: lc[i] = j
if tr[j] == -1: tr[j] = i
for i in range(n):
if tr[i] == -1 and br[i] == n: pre += 1
if lc[i] == -1 and rc[i] == n: pre += 1
for col in range(n-k+1):
tot = 0
for row in range(k):
if lc[row] >= col and rc[row] < col+k: tot += 1
ans[0][col] = tot
for row in range(1, n-k+1):
if lc[row-1] >= col and rc[row-1] < col+k: tot -= 1
if lc[row+k-1] >= col and rc[row+k-1] < col+k: tot += 1
ans[row][col] = tot
for row in range(n-k+1):
tot = 0
for col in range(k):
tot += 1 if tr[col] >= row and br[col] < row+k else 0
post = max(post, ans[row][0]+tot)
for col in range(1, n-k+1):
if tr[col-1] >= row and br[col-1] < row+k: tot -= 1
if tr[col+k-1] >= row and br[col+k-1] < row+k: tot += 1
post = max(post, ans[row][col]+tot)
print(pre+post)
```
| 97,037 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
import sys
def count(n, k, field):
blank = 0
cnt = [[0] * (n - k + 1) for _ in range(n)]
for i, row in enumerate(field):
l = row.find('B')
r = row.rfind('B')
if l == r == -1:
blank += 1
continue
if r - l + 1 > k:
continue
kl = max(0, r - k + 1)
kr = min(l + 1, n - k + 1)
cnt[i][kl:kr] = [1] * (kr - kl)
acc = [[0] * (n - k + 1) for _ in range(n - k + 1)]
t_cnt = list(zip(*cnt))
for i, col in enumerate(t_cnt):
aci = acc[i]
tmp = sum(col[n - k:])
aci[n - k] = tmp
for j in range(n - k - 1, -1, -1):
tmp += col[j]
tmp -= col[j + k]
aci[j] = tmp
return blank, acc
n, k = map(int, input().split())
field = [line.strip() for line in sys.stdin]
bh, hor = count(n, k, field)
t_field = [''.join(col) for col in zip(*field)]
bv, t_var = count(n, k, t_field)
var = list(zip(*t_var))
print(bh + bv + max(h + v for (rh, rv) in zip(hor, var) for (h, v) in zip(rh, rv)))
```
| 97,038 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
n, k = map(int ,input().split())
c_p1 = [[-1] * 2001 for x in range(2001)]
c_p2 = [[-1] * 2001 for x in range(2001)]
r_p1 = [[-1] * 2001 for x in range(2001)]
r_p2 = [[-1] * 2001 for x in range(2001)]
cells = []
for i in range(n):
cells.append(input())
bonus = 0
for y in range(n):
earliest = -1
latest = -1
for x in range(n):
if cells[y][x] == "B":
earliest = x
break
for x in range(n):
if cells[y][n - x - 1] == "B":
latest = n - x - 1
break
if earliest == -1:
bonus += 1
for x in range(n - k + 1):
r_p1[y][x] = int(earliest >= x and x + k - 1 >= latest)
for x in range(n - k + 1):
sum = 0
for y in range(n):
sum += r_p1[y][x]
if y - k >= 0:
sum -= r_p1[y - k][x]
if y - k + 1 >= 0:
r_p2[y - k + 1][x] = sum
for x in range(n):
earliest = -1
latest = -1
for y in range(n):
if cells[y][x] == "B":
earliest = y
break
for y in range(n):
if cells[n - y - 1][x] == "B":
latest = n - y - 1
break
if earliest == -1:
bonus += 1
for y in range(n - k + 1):
c_p1[y][x] = int(earliest >= y and y + k - 1 >= latest)
for y in range(n - k + 1):
sum = 0
for x in range(n):
sum += c_p1[y][x]
if x - k >= 0:
sum -= c_p1[y][x - k]
if x - k + 1 >= 0:
c_p2[y][x - k + 1] = sum
ans = 0
for y in range(n - k + 1):
for x in range(n - k + 1):
ans = max(ans, c_p2[y][x] + r_p2[y][x])
print(ans + bonus)
```
| 97,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().strip()
n, k = map(int, input().split())
arr = []
for i in range(n):
arr.append(list(input()))
extra = 0
res = []
for i in range(n-k+1):
res.append([])
for j in range(n-k+1):
res[-1].append(0)
# ROWS
l = {}
r = {}
for i in range(n):
for j in range(n):
if arr[i][j]=='B': l[i] = j; break
for j in range(n-1, -1, -1):
if arr[i][j]=='B': r[i] = j; break
else: l[i] = None; r[i] = None; extra+=1
for j in range(n-k+1):
tmp = 0
for i in range(k):
if l[i] is not None and l[i]>=j and r[i]<=j+k-1:
tmp+=1
res[0][j]+=tmp
for i in range(1, n-k+1):
if l[i-1] is not None and l[i-1]>=j and r[i-1]<=j+k-1:
tmp-=1
if l[i+k-1] is not None and l[i+k-1]>=j and r[i+k-1]<=j+k-1:
tmp+=1
res[i][j]+=tmp
# COLUMNS
l = {}
r = {}
for j in range(n):
for i in range(n):
if arr[i][j]=='B': l[j] = i; break
for i in range(n-1, -1, -1):
if arr[i][j]=='B': r[j] = i; break
else: l[j] = None; r[j] = None; extra+=1
for i in range(n-k+1):
tmp = 0
for j in range(k):
if l[j] is not None and l[j]>=i and r[j]<=i+k-1:
tmp+=1
res[i][0]+=tmp
for j in range(1, n-k+1):
if l[j-1] is not None and l[j-1]>=i and r[j-1]<=i+k-1:
tmp-=1
if l[j+k-1] is not None and l[j+k-1]>=i and r[j+k-1]<=i+k-1:
tmp+=1
res[i][j]+=tmp
print(max(max(i) for i in res)+extra)
```
| 97,040 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
#sys.setrecursionlimit(300000)
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
#sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
# -----------------------------------------------binary seacrh tree---------------------------------------
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
m=n
l=[]
ans=0
for i in range(n):
l.append(input())
whi=[0 for i in range(n)]
ran=[[-1 for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[i][j]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
ans1=sum(whi)
a=[[0 for i in range(m)]for j in range(n)]
for j in range(m):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[0][j]=cur
for i in range(k,n):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[i-k+1][j]=cur
whi=[0 for i in range(n)]
ran=[[-1for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[j][i]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
b=[[0 for i in range(m)]for j in range(n)]
for j in range(n):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][0]=cur
for i in range(k,m):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][i-k+1]=cur
for i in range(n):
for j in range(m):
ans=max(ans,a[i][j]+b[i][j])
print(ans+sum(whi)+ans1)
```
| 97,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
# pypy 3.6
import re
from collections import deque
from functools import reduce
from fractions import gcd # ~py3.4
from heapq import *
from itertools import permutations
from math import pi
from operator import itemgetter
from operator import mul
from operator import xor
from os import linesep
from sys import stdin
def rline() -> str:
return stdin.readline().rstrip()
def fmatr(matrix, lnsep: str = linesep, fieldsep: str = ' ') -> str:
return lnsep.join(map(lambda row: fieldsep.join(map(str, row)), matrix))
def fbool(boolval: int) -> str:
return ['No', 'Yes'][boolval]
def gcd(a: int, b: int) -> int:
a, b = max([a, b]), min([a, b])
if b == 0:
return a
return gcd(b, a % b)
def solve() -> None:
# read here
n, k = map(int, rline().split())
s = [rline() for i in range(n)]
# solve here
# tb[j], bb[j] = top,bottom black in the column c
# lb[i], rb[i] = leftmost,rightmost black in the row r
tb, bb, lb, rb = [[-1] * n for i in range(4)]
for a in range(n):
hor = s[a]
lb[a] = hor.find('B')
rb[a] = hor.rfind('B')
ver = ''.join(list(map(itemgetter(a), s)))
tb[a] = ver.find('B')
bb[a] = ver.rfind('B')
# print(tb, bb, lb, rb)
ans = 0
df = tb.count(-1)+lb.count(-1)
l4r, r4l = [[{} for i in range(n)] for j in range(2)]
for y in range(k):
l, r = lb[y], rb[y]
if l == -1:
continue
l4r[r][l] = 1 + l4r[r].get(l, 0)
r4l[l][r] = 1 + r4l[l].get(r, 0)
for top in range(n-k+1):
subans = df
btm = top + k # excl.
# erase (0,top)-(k-1,btm-1)
for y in range(top, btm):
if 0 <= lb[y] <= rb[y] < k:
subans += 1
for x in range(k):
if top <= tb[x] <= bb[x] < btm:
subans += 1
ans = max([ans, subans])
# move the eraser right by 1 column
for rm in range(n-k):
ad = rm+k
# remove column
if top <= tb[rm] <= bb[rm] < btm:
subans -= 1
# add column
if top <= tb[ad] <= bb[ad] < btm:
subans += 1
# remove rows
subans -= sum(map(
lambda r: r4l[rm][r] if r < ad else 0, r4l[rm].keys()))
# add rows
subans += sum(map(
lambda l: l4r[ad][l] if l > rm else 0, l4r[ad].keys()))
ans = max([ans, subans])
# print(subans, top, rm)
# udpate r4l, l4r
if rb[top] != -1:
l4r[rb[top]][lb[top]] -= 1
if l4r[rb[top]][lb[top]] == 0:
l4r[rb[top]].pop(lb[top])
r4l[lb[top]][rb[top]] -= 1
if r4l[lb[top]][rb[top]] == 0:
r4l[lb[top]].pop(rb[top])
if btm < n and rb[btm] != -1:
l4r[rb[btm]][lb[btm]] = 1 + l4r[rb[btm]].get(lb[btm], 0)
r4l[lb[btm]][rb[btm]] = 1 + r4l[lb[btm]].get(rb[btm], 0)
# print here
print(ans)
if __name__ == '__main__':
solve()
```
| 97,042 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
n,k=map(int,input().split())
it=[[0]*n for i in range(n)]
t=[[-1,-1] for i in range(n)]
tt=[[-1,-1] for i in range(n)]
for i in range(n):
s=input()
c=-1
cc=-1
for j,ii in enumerate(s):
if ii=="B":
it[i][j]=1
if c==-1:
c=j
cc=j
t[i]=[c,cc]
for i in range(n):
p=[it[j][i] for j in range(n)]
c=-1
cc=-1
for j in range(n):
if p[j]:
if c==-1:
c=j
cc=j
tt[i]=[c,cc]
row_max=[[0]*(n-k+1) for i in range(n-k+1)]
col_max=[[0]*(n-k+1) for i in range(n-k+1)]
for col in range(n-k+1):
s=[0]*n
co=0
for i in range(k):
if t[i]!=[-1,-1]:
if t[i][0]>=col and t[i][0]<=col+k-1 and t[i][1]>=col and t[i][1]<=col+k-1:
co+=1
s[i]=1
row_max[col][0]=co
for row in range(1,n-k+1):
if s[row-1]:
co-=1
i=row+k-1
if t[i]!=[-1,-1]:
if t[i][0]>=col and t[i][0]<=col+k-1 and t[i][1]>=col and t[i][1]<=col+k-1:
co+=1
s[i]=1
row_max[col][row]=co
for row in range(n-k+1):
s=[0]*n
co=0
for i in range(k):
if tt[i]!=[-1,-1]:
if tt[i][0]>=row and tt[i][0]<=row+k-1 and tt[i][1]>=row and tt[i][1]<=row+k-1:
co+=1
s[i]=1
col_max[0][row]=co
for col in range(1,n-k+1):
if s[col-1]:
co-=1
i=col+k-1
if tt[i]!=[-1,-1]:
if tt[i][0]>=row and tt[i][0]<=row+k-1 and tt[i][1]>=row and tt[i][1]<=row+k-1:
co+=1
s[i]=1
col_max[col][row]=co
ma=0
for i in range(n-k+1):
for j in range(n-k+1):
ma=max(ma,row_max[i][j]+col_max[i][j])
ma+=t.count([-1,-1])
ma+=tt.count([-1,-1])
print(ma)
```
| 97,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
def main():
n, k = map(int, input().split())
ss = []
tate = [[0 for _ in range(n+1)] for _ in range(n+1)]
yoko = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(n):
s = input().strip()
for j, _s in enumerate(s):
tate[i+1][j+1] = tate[i][j+1] + (1 if _s == 'B' else 0)
yoko[i+1][j+1] = yoko[i+1][j] + (1 if _s == 'B' else 0)
lc = 0
for i in range(n):
if tate[n][i+1] == 0:
lc += 1
if yoko[i+1][n] == 0:
lc += 1
yans = [[0 for _ in range(n+1)] for _ in range(n+1)]
tans = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(n):
l, r = 0, k
while r <= n:
yans[i+1][l+1] = yans[i][l+1]
if yoko[i+1][n] != 0 and yoko[i+1][r] - yoko[i+1][l] == yoko[i+1][n]:
yans[i+1][l+1] += 1
l += 1
r += 1
for i in range(n):
l, r = 0, k
while r <= n:
tans[l+1][i+1] = tans[l+1][i]
if tate[n][i+1] != 0 and tate[r][i+1] - tate[l][i+1] == tate[n][i+1]:
tans[l+1][i+1] += 1
l += 1
r += 1
ans = lc
for i in range(n-k+1):
for j in range(n-k+1):
ans = max(ans, lc+yans[i+k][j+1]-yans[i][j+1]+tans[i+1][j+k]-tans[i+1][j])
# print(*tate, sep='\n')
# print()
# print(*yoko, sep='\n')
# print()
# print(*tans, sep='\n')
# print()
# print(*yans, sep='\n')
# print()
print(ans)
if __name__ == '__main__':
main()
```
Yes
| 97,044 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,k=map(int,input().split())
MAP=[input().strip() for i in range(n)]
MINR=[1<<30]*n
MAXR=[-1]*n
MINC=[1<<30]*n
MAXC=[-1]*n
for i in range(n):
for j in range(n):
if MAP[i][j]=="B":
MINR[i]=min(MINR[i],j)
MAXR[i]=max(MAXR[i],j)
MINC[j]=min(MINC[j],i)
MAXC[j]=max(MAXC[j],i)
ALWAYS=0
for i in range(n):
if MINR[i]==1<<30 and MAXR[i]==-1:
ALWAYS+=1
if MINC[i]==1<<30 and MAXC[i]==-1:
ALWAYS+=1
ANS=[[0]*(n-k+1) for i in range(n-k+1)]
for j in range(n-k+1):
NOW=0
for i in range(k):
if j<=MINR[i] and j+k-1>=MAXR[i] and MINR[i]!=1<<30 and MAXR[i]!=-1:
NOW+=1
ANS[0][j]+=NOW
for i in range(n-k):
if j<=MINR[i] and j+k-1>=MAXR[i] and MINR[i]!=1<<30 and MAXR[i]!=-1:
NOW-=1
if j<=MINR[i+k] and j+k-1>=MAXR[i+k] and MINR[i+k]!=1<<30 and MAXR[i+k]!=-1:
NOW+=1
ANS[i+1][j]+=NOW
for i in range(n-k+1):
NOW=0
for j in range(k):
if i<=MINC[j] and i+k-1>=MAXC[j] and MINC[j]!=1<<30 and MAXC[j]!=-1:
NOW+=1
ANS[i][0]+=NOW
for j in range(n-k):
if i<=MINC[j] and i+k-1>=MAXC[j] and MINC[j]!=1<<30 and MAXC[j]!=-1:
NOW-=1
if i<=MINC[j+k] and i+k-1>=MAXC[j+k] and MINC[j+k]!=1<<30 and MAXC[j+k]!=-1:
NOW+=1
ANS[i][j+1]+=NOW
print(max([max(a) for a in ANS])+ALWAYS)
```
Yes
| 97,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import sys
import math,bisect
sys.setrecursionlimit(10 ** 5)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
def I(): return int(sys.stdin.readline())
def neo(): return map(int, sys.stdin.readline().split())
def Neo(): return list(map(int, sys.stdin.readline().split()))
N, K = neo()
G = [[1 if s == 'B' else 0 for s in sys.stdin.readline().strip()] for _ in range(N)]
Ans = [[0]*(N+1) for _ in range(N+1)]
ans = 0
for i in range(N):
g = G[i]
if 1 not in g:
ans += 1
continue
r = g.index(1)
l = max(0, N - K - g[::-1].index(1))
j = max(0, i-K+1)
if l <= r:
Ans[j][l] += 1
Ans[j][r+1] -= 1
Ans[i+1][l] -= 1
Ans[i+1][r+1] += 1
G = list(map(list, zip(*G)))
Ans = list(map(list, zip(*Ans)))
for i in range(N):
g = G[i]
if 1 not in g:
ans += 1
continue
r = g.index(1)
l = max(0, N - K - g[::-1].index(1))
j = max(0, i-K+1)
if l <= r:
Ans[j][l] += 1
Ans[j][r+1] -= 1
Ans[i+1][l] -= 1
Ans[i+1][r+1] += 1
Ans = [list(accumulate(g))[::-1] for g in Ans]
Ans = list(map(list, zip(*Ans)))
Ans = [list(accumulate(g))[::-1] for g in Ans]
print(ans + max(max(g) for g in Ans))
```
Yes
| 97,046 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n,k=map(int,input().split())
m=n
l=[]
ans=0
for i in range(n):
l.append(input())
whi=[0 for i in range(n)]
ran=[[-1 for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[i][j]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
ans1=sum(whi)
a=[[0 for i in range(m)]for j in range(n)]
for j in range(m):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[0][j]=cur
for i in range(k,n):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[i-k+1][j]=cur
whi=[0 for i in range(n)]
ran=[[-1for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[j][i]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
b=[[0 for i in range(m)]for j in range(n)]
for j in range(n):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][0]=cur
for i in range(k,m):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][i-k+1]=cur
for i in range(n):
for j in range(m):
ans=max(ans,a[i][j]+b[i][j])
print(ans+sum(whi)+ans1)
```
Yes
| 97,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
n, k = map(int, input().split())
s = [input() for _ in range(n)]
g_row = [[] for _ in range(n)]
g_col = [[] for _ in range(n)]
already_white_line_nums = 0
for i in range(n):
for j in range(n):
if s[i][j] == 'B':
g_row[i].append(j)
g_col[j].append(i)
for i in range(n):
if len(g_row[i]) == 0:
already_white_line_nums += 1
if len(g_col[i]) == 0:
already_white_line_nums += 1
r = already_white_line_nums
for i in range(n - k + 1):
for j in range(n - k + 1):
new_white_line_nums = 0
if len(g_row[i]) == 0 or len(g_col[i]) == 0:
continue
for l in range(i, i + k):
if len(g_row[l]) != 0 and j <= g_row[l][0] and g_row[l][-1] < j + k:
new_white_line_nums += 1
for l in range(j, j + k):
if len(g_col[l]) != 0 and i <= g_col[l][0] and g_col[l][-1] < i + k:
new_white_line_nums += 1
r = max(r, already_white_line_nums + new_white_line_nums)
print(r)
```
No
| 97,048 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import math
# helpful:
# r,g,b=map(int,input().split())
# arr = [[0 for x in range(columns)] for y in range(rows)]
class BIT():
def __init__(self, n):
self.n = n
self.arr = [0]*(n+1)
def update(self, index, val):
while(index <= self.n):
self.arr[index] += val
index += (index & -index)
def cumul(self, index):
if(index == 0):
return 0
total = self.arr[index]
index -= (index & -index)
while(index > 0):
total += self.arr[index]
index -= (index & -index)
return total
def __str__(self):
string = ""
for i in range(self.n):
string += "in spot " + str(i) + ": " + str(self.arr[i]) + "\n"
return string
def get(self, index):
total = self.arr[index]
x = index - (index & -index)
index -= 1
while(index != x):
total -= self.arr[index]
index -= (index & -index)
return total
n,k=map(int,input().split())
arr = [[-1 for x in range(n-k+3)] for y in range(2*n)] # last two cols track smallest and biggest index
for i in range(n):
string = input()
for j in range(n):
if(string[j] == 'B'):
if(arr[i][n-k+1] == -1): # no black ones yet
arr[i][n-k+1] = j
arr[i][n-k+2] = j
elif(arr[i][n-k+1] > j):
arr[i][n-k+1] = j
elif(arr[i][n-k+2] < j):
arr[i][n-k+2] = j
if(arr[n+j][n-k+1] == -1): # no black ones yet
arr[n+j][n-k+1] = i
arr[n+j][n-k+2] = i
elif(arr[n+j][n-k+1] > i):
arr[n+j][n-k+1] = i
elif(arr[n+j][n-k+2] < i):
arr[n+j][n-k+2] = i
for i in range(2*n):
for j in range(n-k+1):
#if(arr[i][n-k+1] == -1):
# arr[i][j] = 1
if(arr[i][n-k+1] >= j and arr[i][n-k+2] <= j+k-1):
arr[i][j] = 1
else:
arr[i][j] = 0
realArr = [BIT(n+2) for x in range(2*n)]
for i in range(2*n):
for j in range(n-k+1):
realArr[i].update(j+1, arr[i][j])
bestOvr = 0
for i in range(n-k+1):
for j in range(n-k+1):
overall = 0
overall += realArr[i].cumul(j+k) - realArr[i].cumul(j)
overall += realArr[n+j].cumul(i+k) - realArr[n+j].cumul(i)
if(overall > bestOvr):
bestOvr = overall
for i in range(2*n):
if(arr[i][n-k+1] == 0):
bestOvr += 1
print(bestOvr)
```
No
| 97,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
sz = n - k + 1
cnt = []
for i in range(sz+1):
cnt.append([0]*(sz+1))
data = []
extra = 0
for i in range(n):
data.append(input())
for r in range(n):
row = data[r]
li = row.find("B") + 1
if li == 0:
extra += 1
continue
ri = row.rfind("B") + 1
for i in range(max(ri - k,1), min(li+1, sz+1)):#??????????????
for j in range(max(1, r+2-k), min(sz+1, r+2)):
cnt[j][i] += 1
# b = []
# b.rindex(1)
for c in range(n):
row = "".join([data[c][i] for i in range(n)])
li = row.find("B") + 1
if li == 0:
extra += 1
continue
ri = row.rfind("B") + 1
for i in range(max(ri - k,1), min(li+1, sz+1)):
for j in range(max(1, c+2-k), min(sz+1, c+2)):
cnt[i][j] += 1
mx = 0
for i in range(1, sz+1):
for j in range(1, sz+1):
if cnt[i][j] > mx:
mx = cnt[i][j]
print(mx+extra)
```
No
| 97,050 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import sys
input = sys.stdin.readline
def getInt(): return int(input())
def getVars(): return map(int, input().split())
def getArr(): return list(map(int, input().split()))
def getStr(): return input().strip()
## -------------------------------
N, K = getVars()
res = N
rows = {}
cols = {}
for i in range(N):
s = getStr()
row = [s.find('B'), s.rfind('B')]
if row[0] == -1:
res += 1
elif row[1] - row[0] < K:
rows[i] = row
for j in range(N):
if s[j] == 'B':
if j not in cols:
cols[j] = [i, i]
res -= 1
else:
cols[j][1] = i
if cols[j][1] - cols[j][0] >= K:
del cols[j]
##print(res)
##print(rows)
##print(cols)
lastiki = {}
for ir in rows:
r = rows[ir]
for lc in range(max(0, r[1] - K + 1), r[0]+1):
for lr in range(max(0, ir-K+1), min(ir+1, N-K+1)):
if lr not in lastiki:
lastiki[lr] = {}
if lc not in lastiki[lr]:
lastiki[lr][lc] = 0
lastiki[lr][lc] += 1
##print(lastiki)
for ic in cols:
c = cols[ic]
for lr in range(max(0, c[1] - K + 1), c[0]+1):
for lc in range(max(0, ic-K+1), min(ic+1, N-K+1)):
if lr not in lastiki:
lastiki[lr] = {}
if lc not in lastiki[lr]:
lastiki[lr][lc] = 0
lastiki[lr][lc] += 1
##print(lastiki)
res1 = 0
for r in lastiki:
res1 = max(res1, max(list(lastiki[r].values())))
print(res+res1)
##
##RES1 = 0
##for lr in range(N-K+1):
## for lc in range(N-K+1):
## res1 = 0
## for ir in range(0, K):
## r = rows[lr + ir]
## if r[0] >= lc and lc + K > r[1]:
#### print('row: ', lr, lc, lr+ir)
## res1 += 1
#### print(lr, lc, res1)
## for ic in range(0, K):
## c = cols[lc + ic]
## if c[0] >= lr and lr + K > c[1]:
## res1 += 1
#### print('col: ', lr, lc, lc+ic)
#### print(lr, lc, res1)
##
## RES1 = max(RES1, res1)
##
##print(res + RES1)
```
No
| 97,051 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
R = lambda: map(int ,input().split())
n, k = R()
xs = list(R())
a = int(input())
cs = list(R())
r = j = 0
try:
for i, x in enumerate(xs):
if x > k:
while x > k:
s = min(cs[:i+1-j])
cs.remove(s)
r += s
j += 1
k += a
if x > k:
raise
except:
print(-1)
quit()
print(r)
```
| 97,052 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
import heapq
n,initial=map(int,input().split())
target=list(map(int,input().split()))
gain=int(input())
prices=list(map(int,input().split()))
flag=True
for i in range(n):
if target[i]>(i+1)*gain+initial:
flag=False
print(-1)
break
if flag:
a=[10**18]
heapq.heapify(a)
maxx=-1
ans=0
for i in range(n):
heapq.heappush(a,prices[i])
if target[i]>initial:
moves=(target[i] - initial - 1)//gain + 1
if moves==0:
break
else:
for i in range(moves):
ans+=heapq.heappop(a)
initial+=gain
print(ans)
```
| 97,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
import heapq
n,k=map(int,input().split())
des=list(map(int,input().split()))
g=int(input())
cost=list(map(int,input().split()))
cos=0
flag=0
cur=k
dec={}
hp=[]
heapq.heapify(hp)
for i in range(n):
dec[i]=0
for i in range(n):
if k+g*(i+1)<des[i]:
flag=1
break
else:
heapq.heappush(hp,cost[i])
while cur<des[i]:
cur+=g
cos+=heapq.heappop(hp)
if flag==1:
print(-1)
else:
print(cos)
```
| 97,054 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
import sys
import os
from io import BytesIO, IOBase
#########################
# imgur.com/Pkt7iIf.png #
#########################
# returns the list of prime numbers less than or equal to n:
'''def sieve(n):
if n < 2: return list()
prime = [True for _ in range(n + 1)]
p = 3
while p * p <= n:
if prime[p]:
for i in range(p * p, n + 1, p):
prime[i] = False
p += 2
r = [2]
for p in range(3, n + 1, 2):
if prime[p]:
r.append(p)
return r'''
# returns all the divisors of a number n(takes an additional parameter start):
'''def divs(n, start=1):
divisors = []
for i in range(start, int(n**.5) + 1):
if n % i == 0:
if n / i == i:
divisors.append(i)
else:
divisors.extend([i, n // i])
return len(divisors)'''
# returns the number of factors of a given number if a primes list is given:
'''def divn(n, primes):
divs_number = 1
for i in primes:
if n == 1:
return divs_number
t = 1
while n % i == 0:
t += 1
n //= i
divs_number *= t
return divs_number'''
# returns the leftmost and rightmost positions of x in a given list d(if x isnot present then returns (-1,-1)):
'''def flin(d, x, default=-1):
left = right = -1
for i in range(len(d)):
if d[i] == x:
if left == -1: left = i
right = i
if left == -1:
return (default, default)
else:
return (left, right)'''
#count xor of numbers from 1 to n:
'''def xor1_n(n):
d={0:n,1:1,2:n+1,3:0}
return d[n&3]'''
def cel(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return defaultdict(int)
def ddl(): return defaultdict(list)
def ddd(): return defaultdict(defaultdict(int))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict
#from collections import deque
#from collections import OrderedDict
#from math import gcd
#import time
#import itertools
#import timeit
#import random
#from bisect import bisect_left as bl
#from bisect import bisect_right as br
#from bisect import insort_left as il
#from bisect import insort_right as ir
from heapq import *
from queue import PriorityQueue
#mod=998244353
#mod=10**9+7
# for counting path pass prev as argument:
# for counting level of each node w.r.t to s pass lvl instead of prev:
n,k=mi()
X=li()
A=ii()
C=li()
ans=0
cost=[]
for i in range(n):
req=((X[i]-k)//A)+((X[i]-k)%A!=0)
heappush(cost,C[i])
if req>len(cost):
ans=-1
break
else:
for j in range(req):
ans+=heappop(cost)
k+=A
print(ans)
```
| 97,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify
def main():
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
for _ in range(1):
n,k=ria()
x=ria()
a=ri()
c=ria()
mcum=[]
heapmcum=heapify(mcum)
m=9999999999999999999999
spent=0
for i in range(n):
cost=0
heappush(mcum,c[i])
if k<x[i]:
while k<x[i]:
if len(mcum)==0:
spent=-1
break
cost+=heappop(mcum)
k+=a
if spent==-1:
break
spent+=cost
print(spent)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
```
| 97,056 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
def main():
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
for _ in range(1):
n,k=ria()
x=ria()
a=ri()
c=ria()
mcum=deque([])
m=9999999999999999999999
spent=0
for i in range(n):
cost=0
mcum.append(c[i])
mcum=deque(sorted(mcum))
if k<x[i]:
while k<x[i]:
if len(mcum)==0:
spent=-1
break
cost+=mcum[0]
mcum.popleft()
k+=a
if spent==-1:
break
spent+=cost
print(spent)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
```
| 97,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
from math import ceil
from heapq import heappush, heapify, heappop
n,x = [int(i) for i in input().split()]
l = [int(i) for i in input().split()]
a = int(input())
c = [int(i) for i in input().split()]
for i in range(n):
l[i] = ceil((l[i]-x)/a)
# print(l)
cost = 0
flag = True
heap = []
till = 0
for i in range(n):
heappush(heap,c[i])
# if l[i]>len(heap):
l[i] = max(l[i]-till, 0)
while(l[i]>0 and heap):
k = heappop(heap)
cost+=k
l[i]-=1
till+=1
if l[i]>0:
flag = False
break
if flag:
print(cost)
else:
print(-1)
```
| 97,058 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Tags: data structures, greedy
Correct Solution:
```
import heapq
def process(n, k, X, a, C):
res=0
A=[]
for i in range(len(X)):
heapq.heappush(A, C[i])
if k+len(A)*a < X[i]:
return -1
else:
while k <X[i]:
res+=heapq.heappop(A)
k+=a
return res
n, k=[int(x) for x in input().split()]
X=[int(x) for x in input().split()]
a=int(input())
C=[int(x) for x in input().split()]
print(process(n,k,X,a,C))
```
| 97,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
import heapq
n,k=map(int,input().split())
lis=list(map(int,input().split()))
energy=int(input())
cost=list(map(int,input().split()))
h=[]
length=len(lis)
output=0
for i in range(length):
heapq.heappush(h,cost[i])
if lis[i]>k:
while(h):
if k>=lis[i]:
break
output+=heapq.heappop(h)
k+=energy
if k<lis[i]:
print(-1)
break
else:
print(output)
```
Yes
| 97,060 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
import heapq as hp
import sys
n, k = map(int, input().split())
arr = list(map(int, input().split()))
p = int(input())
arrx = list(map(int, input().split()))
prev = []
hp.heapify(prev)
cost = 0
flag = 0
for i in range(n):
hp.heappush(prev, arrx[i])
while arr[i] > k and len(prev) > 0:
k += p
cost += hp.heappop(prev)
if k < arr[i]:
flag = 1
break
if flag == 1:
print(-1)
else:
print(cost)
```
Yes
| 97,061 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
n, k = map(int, input().split())
P = list(map(int, input().split()))
from heapq import *
A = int(input())
c = list(map(int, input().split()))
cur = []
cost = 0
for i, p in enumerate(P):
heappush(cur, c[i])
if p > k:
if len(cur)*A + k < p:
cost = -1
break
else:
while p > k:
cost += heappop(cur)
k += A
print(cost)
```
Yes
| 97,062 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
N,K = map(int,input().split())
X = list(map(int,input().split()))
A = int(input())
C = list(map(int,input().split()))
available_drinks = []
total_cost = 0
ability = K
for i in range(N):
available_drinks.append(C[i])
if ability < X[i]:
drinks_needed = (X[i] - ability - 1) // A + 1
if drinks_needed > len(available_drinks):
print(-1)
break
available_drinks.sort()
total_cost += sum(available_drinks[:drinks_needed])
available_drinks = available_drinks[drinks_needed:]
ability += A * drinks_needed
else:
print(total_cost)
```
Yes
| 97,063 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
import heapq
import math
n,k = list(map(int,input().split()))
x = list(map(int,input().split()))
a = int(input())
c = list(map(int,input().split()))
maxx = max(x)
fx = x.index(maxx)
delta = maxx-k
if delta<=0:
print(0)
elif delta/(fx+1) > a:
print(-1)
else:
v = math.ceil(delta/a)
x = x[:fx+1]
c = c[:fx+1]
out = 0
x1 = x[:]
for i in range(fx-1,-1,-1):
x1[i]=max(x[i],x1[i+1]-a)
minv = []
for i in range(fx+1):
heapq.heappush(minv,c[i])
if k<x1[i]:
k+=a
out += heapq.heappop(minv)
print(out)
```
No
| 97,064 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
import sys, math
input = lambda: sys.stdin.readline().strip("\r\n")
n, k = map(int, input().split())
x = list(map(int, input().split()))
a = int(input())
c = list(map(int, input().split()))
ans = 0
left = []
ref = k
if k + a < x[0]:
print(-1)
exit()
elif k + a == x[0]:
ans += c[0]
k += a
for i in range(n-1):
if ref <= x[i + 1] - k <= ref + a:
k += a
ans += c[i+1]
elif x[i+1] - k < 0:
continue
elif 0 <= x[i+1] - k <= ref:
left.append(i+1)
else:
if len(left) > 0 and x[i+1] - k <= a * len(left):
req = math.ceil((x[i] - k) / a)
if req <= len(left):
left.sort()
# k += left[:req]
for i in range(req):
k += left[i]
ans += c[left[i]]
else:
print(-1)
exit()
else:
print(-1)
exit()
print(ans)
```
No
| 97,065 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
# from debug import debug
import sys;input = sys.stdin.readline
n, k = map(int, input().split())
lis = list(map(int, input().split()))
a = int(input())
c = list(map(int, input().split()))
cost = 0
for j, i in enumerate(lis):
if i>k:
if i>k+a:
print(-1); sys.exit()
cost += c[j]
k+=a
print(cost)
```
No
| 97,066 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 β€ N β€ 10^5) and K (1 β€ K β€ 10^5) β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 β€ X[i] β€ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 β€ A β€ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 β€ C[i] β€ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
Submitted Solution:
```
import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
stdin, stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def iinp(): return int(inp())
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def ceil(a, b): return (a+b-1)//b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return False
return True
n, k = mp()
arr = lmp()
a = iinp()
cost = lmp()
hp = []
ans = 0
flg = True
for i in range(n):
if k >= arr[i]:
heappush(hp, cost[i])
else:
while hp and k < arr[i]:
k += a
ans += heappop(hp)
if k < arr[i]:
flg = False
break
print(ans if flg else -1)
```
No
| 97,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
import sys
n = sys.stdin.readline()
n = int(n)
def get_graph(n):
graph = []
for _ in range(n):
entries = list(map(lambda x : int(x), sys.stdin.readline().split(" ")[1:]))
graph.append(entries)
return graph
def chain(target, buckets, reverse_bucket, sum_bucket, bucket_num, val):
mask = 2**bucket_num
mem = []
buckets_seen = set({bucket_num})
og_bucket = bucket_num
og_val = val
for _ in range(len(buckets)):
rem = target - sum_bucket[bucket_num] + val
if rem not in reverse_bucket:
return None, []
new_bucket = reverse_bucket[rem]
if new_bucket == og_bucket and rem != og_val:
return None, []
elif new_bucket == og_bucket and rem == og_val:
mem.append((rem, bucket_num))
return mask | 2**new_bucket, mem
elif new_bucket in buckets_seen:
return None, []
buckets_seen.add(new_bucket)
mask = mask | 2**new_bucket
mem.append((rem, bucket_num))
bucket_num = new_bucket
val = rem
return None, []
#mask is what you wanna see if you can get
def helper(chains, mask, mem):
if mask == 0:
return []
if mask in mem:
return mem[mask]
for i, chain in enumerate(chains):
if (mask >> i) & 0:
continue
for key in chain:
if key | mask != mask:
continue
future = helper(chains, ~key & mask, mem)
if future is not None:
mem[mask] = chain[key] + future
return mem[mask]
mem[mask] = None
return None
def solve(n):
buckets = get_graph(n)
reverse_bucket = {}
sum_bucket = [0]* len(buckets)
total_sum = 0
for i, bucket in enumerate(buckets):
for x in bucket:
total_sum += x
sum_bucket[i] += x
reverse_bucket[x] = i
target = total_sum / len(buckets)
chains = []
for i, bucket in enumerate(buckets):
seto = {}
for x in bucket:
key, val = chain(target, buckets, reverse_bucket, sum_bucket, i, x)
if key is not None:
seto[key] = val
chains.append(seto)
mem = {}
for i in range (2**len(buckets)-1):
helper(chains, i, mem)
return helper(chains, 2 ** len(buckets) - 1, mem), reverse_bucket
def result(n):
res, reverse_bucket = solve(n)
if res is None:
sys.stdout.write("No\n")
else:
res = sorted(res, key = lambda x : reverse_bucket[x[0]])
sys.stdout.write("Yes\n")
for x, y in res:
x = int(x)
y = int(y) + 1
stuff = " ".join([str(x), str(y), "\n"])
sys.stdout.write(stuff)
result(n)
```
| 97,068 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
from collections import defaultdict
data = defaultdict(list)
position = defaultdict()
nxt = defaultdict()
agg_sum = list()
k = int(input())
trace = defaultdict()
F = [False for x in range(1 << k)]
back = [0 for x in range(1 << k)]
total_sum = 0
res = [(0, 0) for x in range(k)]
def build_mask(trace_mask):
if trace_mask == 0:
return
if trace.get(trace_mask):
for data in trace.get(trace_mask):
fr, to, v = data
res[fr] = (v, to)
return
sub_mask = back[trace_mask]
build_mask(sub_mask)
build_mask(trace_mask - sub_mask)
if __name__ == '__main__':
for i in range(k):
values = list(map(int, input().split(' ')))
data[i] = values[1:]
agg_sum.append(sum(data[i]))
total_sum += agg_sum[i]
for cnt, v in enumerate(data[i], 0):
position[v] = (i, cnt)
if total_sum % k != 0:
print("No")
exit(0)
row_sum = total_sum // k
for i in range(k):
for cnt, value in enumerate(data.get(i), 0):
x = i
y = cnt
mask = (1 << x)
could = True
circle = list()
while True:
next_value = row_sum - agg_sum[x] + data.get(x)[y]
if position.get(next_value) is None:
could = False
break
last_x = x
last_y = y
x, y = position.get(next_value)
circle.append((x, last_x, next_value))
if x == i and y == cnt:
break
if mask & (1 << x):
could = False
break
mask |= (1 << x)
F[mask] |= could
if could:
trace[mask] = circle
for mask in range(1, 1 << k):
sub = mask
while sub > 0:
if F[sub] and F[mask - sub]:
F[mask] = True
back[mask] = sub
break
sub = mask & (sub - 1)
if F[(1 << k) - 1]:
print('Yes')
build_mask((1 << k) - 1)
for value in res:
print(value[0], value[1] + 1)
else:
print('No')
```
| 97,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
simple = [False]*(1 << k)
answer = [False]*(1 << k)
left = [0]*(1 << k)
right = [0]*(1 << k)
by_last_one = [[] for _ in range(k)]
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, [])
if found and not answer[mask]:
answer[mask] = True
masks[mask] = path
simple[mask] = True
by_last_one[calc_last_one(mask)].append(mask)
if answer[(1 << k) - 1]:
return build_answer(k, masks, left, right)
for mask_right in range(2, 1 << k):
if not simple[mask_right]:
continue
last_one = calc_last_one(mask_right)
zeroes_count = 0
alternative_sum = 0
zero_list = []
for u in range(last_one):
if (mask_right & (1 << u)) == 0:
zeroes_count += 1
alternative_sum += len(by_last_one[u])
zero_list.append(u)
if zeroes_count == 0:
continue
if alternative_sum < (1 << zeroes_count):
for fill_last_zero in zero_list:
for mask_left in by_last_one[fill_last_zero]:
if (mask_left & mask_right) != 0:
continue
joint_mask = mask_left | mask_right
if not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
by_last_one[last_one].append(joint_mask)
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
else:
for mask_mask in range(1 << zeroes_count):
mask_left = 0
for u in range(zeroes_count):
if (mask_mask & (1 << u)) != 0:
mask_left = mask_left | (1 << zero_list[u])
joint_mask = mask_left | mask_right
if answer[mask_left] and not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
by_last_one[last_one].append(joint_mask)
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
return False, None, None
def calc_last_one(x):
result = -1
while x > 0:
x = x >> 1
result = result + 1
return result
def build_answer(k, masks, left, right):
c = [-1] * k
p = [-1] * k
pos = (1 << k) - 1
while not masks[pos]:
for i, a, j in masks[right[pos]]:
c[i] = a
p[i] = j
pos = left[pos]
for i, a, j in masks[pos]:
c[i] = a
p[i] = j
return True, c, p
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path.append((i_next, a[i_next][j_next], i))
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
if __name__ == "__main__":
main()
```
| 97,070 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
simple = [False]*(1 << k)
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, dict())
if found:
simple[mask] = True
masks[mask] = path
for i in range(1 << k):
if not simple[i]:
continue
mask = i
zeroes_count = 0
for u in range(k):
if (1 << u) > mask:
break
if (mask & (1 << u)) == 0:
zeroes_count += 1
for mask_mask in range(1 << zeroes_count):
mask_child = 0
c = 0
for u in range(k):
if (1 << u) > mask:
break
if (mask & (1 << u)) == 0:
if (mask_mask & (1 << c)) != 0:
mask_child = mask_child | (1 << u)
c += 1
if masks[mask_child] and not masks[mask_child | mask]:
masks[mask_child | mask] = {**masks[mask_child], **masks[mask]}
if (mask_child | mask) == ((1 << k) - 1):
c = [-1] * k
p = [-1] * k
d = masks[(1 << k) - 1]
for key, val in d.items():
c[key] = val[0]
p[key] = val[1]
return True, c, p
if masks[(1 << k) - 1]:
c = [-1] * k
p = [-1] * k
d = masks[(1 << k) - 1]
for key, val in d.items():
c[key] = val[0]
p[key] = val[1]
return True, c, p
return False, None, None
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path[i_next] = (a[i_next][j_next], i)
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
if __name__ == "__main__":
main()
```
| 97,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
k = int(input())
d = {}
aa = []
sa = []
for i in range(k):
ni, *a = map(int, input().split())
for ai in a:
d[ai] = i
aa.append(a)
sa.append(sum(a))
s = sum(sa)
if s%k != 0:
print("No")
exit()
s //= k
def calc_next(i, aij):
bij = s-sa[i]+aij
if bij not in d:
return -1, bij
else:
return d[bij], bij
def loop_to_num(loop):
ret = 0
for i in reversed(range(k)):
ret <<= 1
ret += loop[i]
return ret
loop_dict = {}
used = set()
for i in range(k):
for aij in aa[i]:
if aij in used:
continue
loop = [0]*k
num = [float("Inf")]*k
start_i = i
start_aij = aij
j = i
loop[j] = 1
num[j] = aij
used.add(aij)
exist = False
for _ in range(100):
j, aij = calc_next(j, aij)
if j == -1:
break
#used.add(aij)
if loop[j] == 0:
loop[j] = 1
num[j] = aij
else:
if j == start_i and aij == start_aij:
exist = True
break
if exist:
m = loop_to_num(loop)
loop_dict[m] = tuple(num)
for numi in num:
if numi != float("inf"):
used.add(numi)
mask = 1<<k
for state in range(1, mask):
if state in loop_dict:
continue
j = (state-1)&state
while j:
i = state^j
if i in loop_dict and j in loop_dict:
tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k))
loop_dict[state] = tp
break
j = (j-1)&state
if mask-1 not in loop_dict:
print("No")
else:
print("Yes")
t = loop_dict[mask-1]
ns = [sa[i]-t[i] for i in range(k)]
need = [s - ns[i] for i in range(k)]
for i in range(k):
print(t[i], need.index(t[i])+1)
```
| 97,072 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
from itertools import accumulate
from sys import stdin, stdout
def main():
k = int(stdin.readline())
a = [
tuple(map(int, stdin.readline().split()[1:]))
for _ in range(k)
]
a2ij = {
aij: (i, j)
for i, ai in enumerate(a)
for j, aij in enumerate(ai)
}
plena = [0, ] + list(accumulate(map(len, a)))
suma = tuple(map(sum, a))
totala = sum(suma)
if totala % k != 0:
stdout.write("No\n")
else:
needle = totala // k
mask2i2cp = compute_mask2i2cp(a, a2ij, needle, plena, suma)
dp = compute_previous_mask(mask2i2cp)
output(dp, mask2i2cp)
def compute_mask2i2cp(a, a2ij, needle, plena, suma):
used = [False, ] * plena[-1]
number_of_masks = 1 << len(a)
mask2i2cp = [-1, ] * number_of_masks
for i, ai in enumerate(a):
for j, aij in enumerate(ai):
if not used[plena[i] + j]:
mask, i2cp = compute_mask_i2cp(a2ij, aij, i, j, needle, suma)
if i2cp != -1:
mask2i2cp[mask] = i2cp
return mask2i2cp
def output(dp, mask2i2cp):
mask = len(mask2i2cp) - 1
if dp[mask] == -1:
stdout.write("No\n")
else:
answer = [-1, ] * len(mask2i2cp[dp[mask]])
while mask > 0:
current_mask = dp[mask]
for i, cp in enumerate(mask2i2cp[current_mask]):
if 1 == ((current_mask >> i) & 1):
c, p = cp
answer[i] = (c, p)
mask ^= current_mask
stdout.write('Yes\n' + '\n'.join('{} {}'.format(c, 1 + p) for c, p in answer))
def compute_mask_i2cp(a2ij, aij, i, j, needle, suma):
i2cp = [-1, ] * len(suma)
mask = 0
current_a = aij
current_i = i
try:
while True:
next_a = needle - (suma[current_i] - current_a)
next_i, next_j = a2ij[next_a]
if ((mask >> next_i) & 1) == 1:
return mask, -1
mask |= 1 << next_i
i2cp[next_i] = (next_a, current_i)
if next_i == i:
if next_j == j:
return mask, i2cp
return mask, -1
if next_i == current_i:
return mask, -1
current_a = next_a
current_i = next_i
except KeyError:
return mask, -1
def compute_previous_mask(mask2cp):
number_of_masks = len(mask2cp)
dp = [-1, ] * number_of_masks
dp[0] = 0
for mask, cp in enumerate(mask2cp):
if cp != -1:
complement_mask = (number_of_masks - 1) & (~mask)
previous_mask = complement_mask
while previous_mask > 0:
if dp[previous_mask] != -1 and dp[previous_mask | mask] == -1:
dp[previous_mask | mask] = mask
previous_mask = (previous_mask - 1) & complement_mask
if dp[mask] == -1:
dp[mask] = mask
return dp
if __name__ == '__main__':
main()
```
| 97,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
from itertools import accumulate
from sys import stdin, stdout
def main():
k = int(stdin.readline())
a = [
tuple(map(int, stdin.readline().split()[1:]))
for _ in range(k)
]
a2ij = {
aij: (i, j)
for i, ai in enumerate(a)
for j, aij in enumerate(ai)
}
plena = [0, ] + list(accumulate(map(len, a)))
suma = tuple(map(sum, a))
totala = sum(suma)
if totala % k != 0:
stdout.write("No\n")
else:
needle = totala // k
mask2i2cp = compute_mask2i2cp(a, a2ij, needle, plena, suma)
dp = compute_previous_mask(mask2i2cp)
output(dp, mask2i2cp)
def compute_mask2i2cp(a, a2ij, needle, plena, suma):
used = [False, ] * plena[-1]
number_of_masks = 1 << len(a)
mask2i2cp = [-1, ] * number_of_masks
for i, ai in enumerate(a):
for j, aij in enumerate(ai):
if not used[plena[i] + j]:
mask, i2cp = compute_mask_i2cp(a2ij, aij, i, j, needle, suma)
if i2cp != -1:
mask2i2cp[mask] = i2cp
for cp in i2cp:
if cp != -1:
c, p = cp
ii, jj = a2ij[c]
used[plena[ii] + jj] = True
return mask2i2cp
def output(dp, mask2i2cp):
mask = len(mask2i2cp) - 1
if dp[mask] == -1:
stdout.write("No\n")
else:
answer = [-1, ] * len(mask2i2cp[dp[mask]])
while mask > 0:
current_mask = dp[mask]
for i, cp in enumerate(mask2i2cp[current_mask]):
if 1 == ((current_mask >> i) & 1):
c, p = cp
answer[i] = (c, p)
mask ^= current_mask
stdout.write('Yes\n' + '\n'.join('{} {}'.format(c, 1 + p) for c, p in answer))
def compute_mask_i2cp(a2ij, aij, i, j, needle, suma):
i2cp = [-1, ] * len(suma)
mask = 0
current_a = aij
current_i = i
try:
while True:
next_a = needle - (suma[current_i] - current_a)
next_i, next_j = a2ij[next_a]
if ((mask >> next_i) & 1) == 1:
return mask, -1
mask |= 1 << next_i
i2cp[next_i] = (next_a, current_i)
if next_i == i:
if next_j == j:
return mask, i2cp
return mask, -1
if next_i == current_i:
return mask, -1
current_a = next_a
current_i = next_i
except KeyError:
return mask, -1
def compute_previous_mask(mask2cp):
number_of_masks = len(mask2cp)
dp = [-1, ] * number_of_masks
dp[0] = 0
for mask, cp in enumerate(mask2cp):
if cp != -1:
complement_mask = (number_of_masks - 1) & (~mask)
previous_mask = complement_mask
while previous_mask > 0:
if dp[previous_mask] != -1 and dp[previous_mask | mask] == -1:
dp[previous_mask | mask] = mask
previous_mask = (previous_mask - 1) & complement_mask
if dp[mask] == -1:
dp[mask] = mask
return dp
if __name__ == '__main__':
main()
```
| 97,074 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
import sys
n = sys.stdin.readline()
n = int(n)
def get_graph(n):
graph = []
for _ in range(n):
entries = list(map(lambda x : int(x), sys.stdin.readline().split(" ")[1:]))
graph.append(entries)
return graph
def chain(target, buckets, reverse_bucket, sum_bucket, bucket_num, val):
mask = 2**bucket_num
mem = []
buckets_seen = set({bucket_num})
og_bucket = bucket_num
og_val = val
for _ in range(len(buckets)):
rem = target - sum_bucket[bucket_num] + val
if rem not in reverse_bucket:
return None, []
new_bucket = reverse_bucket[rem]
if new_bucket == og_bucket and rem != og_val:
return None, []
elif new_bucket == og_bucket and rem == og_val:
mem.append((rem, bucket_num))
return mask | 2**new_bucket, mem
elif new_bucket in buckets_seen:
return None, []
buckets_seen.add(new_bucket)
mask = mask | 2**new_bucket
mem.append((rem, bucket_num))
bucket_num = new_bucket
val = rem
return None, []
#mask is what you wanna see if you can get
def helper(chains, mask, mem):
if mask == 0:
return []
if mask in mem:
return mem[mask]
for i, chain in enumerate(chains):
if (mask >> i) & 0:
continue
for key in chain:
if key | mask != mask:
continue
future = helper(chains, ~key & mask, mem)
if future is not None:
mem[mask] = chain[key] + future
return mem[mask]
mem[mask] = None
return None
def solve(n):
buckets = get_graph(n)
reverse_bucket = {}
sum_bucket = [0]* len(buckets)
total_sum = 0
for i, bucket in enumerate(buckets):
for x in bucket:
total_sum += x
sum_bucket[i] += x
reverse_bucket[x] = i
target = total_sum / len(buckets)
chains = []
for i, bucket in enumerate(buckets):
seto = {}
for x in bucket:
key, val = chain(target, buckets, reverse_bucket, sum_bucket, i, x)
if key is not None:
seto[key] = val
chains.append(seto)
return helper(chains, 2 ** len(buckets) - 1, {}), reverse_bucket
def result(n):
res, reverse_bucket = solve(n)
if res is None:
sys.stdout.write("No\n")
else:
res = sorted(res, key = lambda x : reverse_bucket[x[0]])
sys.stdout.write("Yes\n")
for x, y in res:
x = int(x)
y = int(y) + 1
stuff = " ".join([str(x), str(y), "\n"])
sys.stdout.write(stuff)
result(n)
```
| 97,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Submitted Solution:
```
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
answer = [False]*(1 << k)
left = [0]*(1 << k)
right = [0]*(1 << k)
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, dict())
if found:
answer[mask] = True
masks[mask] = path
for mask_right in range(1 << k):
if not masks[mask_right]:
continue
zeroes_count = 0
for u in range(k):
if (1 << u) > mask_right:
break
if (mask_right & (1 << u)) == 0:
zeroes_count += 1
for mask_mask in range(1 << zeroes_count):
mask_left = 0
c = 0
for u in range(k):
if (1 << u) > mask_right:
break
if (mask_right & (1 << u)) == 0:
if (mask_mask & (1 << c)) != 0:
mask_left = mask_left | (1 << u)
c += 1
joint_mask = mask_left | mask_right
if answer[mask_left] and not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
if answer[(1 << k) - 1]:
return build_answer(k, masks, left, right)
return False, None, None
def build_answer(k, masks, left, right):
c = [-1] * k
p = [-1] * k
pos = (1 << k) - 1
while not masks[pos]:
for key, val in masks[right[pos]].items():
c[key] = val[0]
p[key] = val[1]
pos = left[pos]
for key, val in masks[pos].items():
c[key] = val[0]
p[key] = val[1]
return True, c, p
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path[i_next] = (a[i_next][j_next], i)
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
if __name__ == "__main__":
main()
```
Yes
| 97,076 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Submitted Solution:
```
import sys
n = sys.stdin.readline()
n = int(n)
def get_graph(n):
graph = []
for _ in range(n):
entries = list(map(lambda x : int(x), sys.stdin.readline().split(" ")[1:]))
graph.append(entries)
return graph
#run is binary arr
def helper(target, buckets, reverse_bucket, sum_bucket, mem, mask, run):
if ~mask in mem:
return mem[mask] + run
main = None
curr = mask
count = len(buckets) - 1
while count >= 0:
if curr & 1 == 0:
main = count
break
curr = curr >> 1
count -= 1
if main is None:
return run
for x in buckets[main]:
new_run = set()
buckets_seen = set()
running_bucket = main
new_mask = mask
fucked = False
while True:
val = target - (sum_bucket[running_bucket] - x)
if val not in reverse_bucket:
break
new_bucket = reverse_bucket[val]
if new_bucket == running_bucket and x != val:
break
if (val, running_bucket) not in new_run and running_bucket not in buckets_seen:
if (mask >> (len(buckets)-1-new_bucket)) & 1 == 1:
fucked = True
x = val
new_run.add((val, running_bucket))
buckets_seen.add(running_bucket)
running_bucket = new_bucket
new_mask = new_mask | 2**(len(buckets)-1-new_bucket)
elif (val, running_bucket) not in new_run and running_bucket in buckets_seen:
break
elif (val, running_bucket) in new_run and running_bucket in buckets_seen:
mem[new_mask] = list(new_run)
if fucked:
return
run.extend(list(new_run))
return helper(target, buckets, reverse_bucket, sum_bucket, mem, new_mask, run)
def solve(n):
buckets = get_graph(n)
reverse_bucket = {}
sum_bucket = [0]* len(buckets)
total_sum = 0
for i, bucket in enumerate(buckets):
for x in bucket:
total_sum += x
sum_bucket[i] += x
reverse_bucket[x] = i
target = total_sum / len(buckets)
mem = {}
run = []
return helper(target, buckets, reverse_bucket, sum_bucket, mem, 0, run)
def result(n):
res = solve(n)
if res is None:
sys.stdout.write("No\n")
else:
sys.stdout.write("Yes\n")
for x, y in res:
x = int(x)
y += 1
stuff = " ".join([str(x), str(y), "\n"])
sys.stdout.write(stuff)
result(n)
```
No
| 97,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Submitted Solution:
```
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
simple = [False]*(1 << k)
answer = [False]*(1 << k)
left = [0]*(1 << k)
right = [0]*(1 << k)
by_last_one = [[] for _ in range(k)]
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, [])
if found and not answer[mask]:
answer[mask] = True
masks[mask] = path
simple[mask] = True
by_last_one[calc_last_one(mask)].append(mask)
if answer[(1 << k) - 1]:
return build_answer(k, masks, left, right)
for mask_right in range(2, 1 << k):
if not simple[mask_right]:
continue
last_one = calc_last_one(mask_right)
zeroes_count = 0
last_zero = -1
u1 = 1
for u in range(last_one):
if (mask_right & u1) == 0:
zeroes_count += 1
last_zero = u
u1 *= 2
if zeroes_count == 0:
continue
if 0 * len(by_last_one[last_zero]) < (1 << zeroes_count):
for mask_left in by_last_one[last_zero]:
if (mask_left & mask_right) != 0:
continue
joint_mask = mask_left | mask_right
if not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
by_last_one[last_one].append(joint_mask)
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
else:
for mask_mask in range(1 << zeroes_count):
mask_left = 0
c1 = 1
u1 = 1
for u in range(last_zero + 1):
if (mask_right & u1) == 0:
if (mask_mask & c1) != 0:
mask_left = mask_left | u1
c1 *= 2
u1 *= 2
joint_mask = mask_left | mask_right
if answer[mask_left] and not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
by_last_one[last_one].append(joint_mask)
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
return False, None, None
def calc_last_one(x):
result = -1
while x > 0:
x = x >> 1
result = result + 1
return result
def build_answer(k, masks, left, right):
c = [-1] * k
p = [-1] * k
pos = (1 << k) - 1
while not masks[pos]:
for i, a, j in masks[right[pos]]:
c[i] = a
p[i] = j
pos = left[pos]
for i, a, j in masks[pos]:
c[i] = a
p[i] = j
return True, c, p
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path.append((i_next, a[i_next][j_next], i))
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
if __name__ == "__main__":
main()
```
No
| 97,078 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Submitted Solution:
```
import sys
n = sys.stdin.readline()
n = int(n)
def get_graph(n):
graph = []
for _ in range(n):
entries = list(map(lambda x : int(x), sys.stdin.readline().split(" ")[1:]))
graph.append(entries)
return graph
#run is binary arr
def helper(target, buckets, reverse_bucket, sum_bucket, mem, mask, run):
if ~mask in mem:
return mem[mask] + run
main = None
curr = mask
count = len(buckets) - 1
while count >= 0:
if curr & 1 == 0:
main = count
break
curr = curr >> 1
count -= 1
if main is None:
return run
for x in buckets[main]:
new_run = set()
buckets_seen = set()
running_bucket = main
new_mask = mask
fucked = False
while True:
val = target - (sum_bucket[running_bucket] - x)
if val not in reverse_bucket:
break
new_bucket = reverse_bucket[val]
if new_bucket == running_bucket and x != val:
break
if (val, running_bucket) not in new_run and running_bucket not in buckets_seen:
if (mask >> (len(buckets)-1-new_bucket)) & 1 == 1:
fucked = True
x = val
new_run.add((val, running_bucket))
buckets_seen.add(running_bucket)
running_bucket = new_bucket
new_mask = new_mask | 2**(len(buckets)-1-new_bucket)
elif (val, running_bucket) not in new_run and running_bucket in buckets_seen:
break
elif (val, running_bucket) in new_run and running_bucket in buckets_seen:
mem[new_mask] = list(new_run)
if fucked:
break
run.extend(list(new_run))
return helper(target, buckets, reverse_bucket, sum_bucket, mem, new_mask, run)
def solve(n):
buckets = get_graph(n)
reverse_bucket = {}
sum_bucket = [0]* len(buckets)
total_sum = 0
for i, bucket in enumerate(buckets):
for x in bucket:
total_sum += x
sum_bucket[i] += x
reverse_bucket[x] = i
target = total_sum / len(buckets)
mem = {}
run = []
return helper(target, buckets, reverse_bucket, sum_bucket, mem, 0, run), reverse_bucket
def result(n):
res, reverse_bucket = solve(n)
if res is None:
sys.stdout.write("No\n")
else:
res = sorted(res, key = lambda x : reverse_bucket[x[0]])
sys.stdout.write("Yes\n")
for x, y in res:
x = int(x)
y += 1
stuff = " ".join([str(x), str(y), "\n"])
sys.stdout.write(stuff)
result(n)
```
No
| 97,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers β one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 β€ k β€ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 β€ n_i β€ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, β¦, a_{i,n_i} (|a_{i,j}| β€ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Submitted Solution:
```
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
simple = [False]*(1 << k)
answer = [False]*(1 << k)
left = [0]*(1 << k)
right = [0]*(1 << k)
by_last_one = [[] for _ in range(k)]
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, [])
if found:
answer[mask] = True
masks[mask] = path
simple[mask] = True
by_last_one[calc_last_one(mask)].append(mask)
if answer[(1 << k) - 1]:
return build_answer(k, masks, left, right)
for mask_right in range(2, 1 << k):
if not simple[mask_right]:
continue
last_one = calc_last_one(mask_right)
zeroes_count = 0
last_zero = -1
u1 = 1
for u in range(last_one):
if (mask_right & u1) == 0:
zeroes_count += 1
last_zero = u
u1 *= 2
if zeroes_count == 0:
continue
if len(by_last_one[last_zero]) < (1 << zeroes_count):
for mask_left in by_last_one[last_zero]:
if (mask_left & mask_right) != 0:
continue
joint_mask = mask_left | mask_right
if not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
by_last_one[last_one].append(joint_mask)
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
else:
for mask_mask in range(1 << zeroes_count):
mask_left = 0
c1 = 1
u1 = 1
for u in range(last_zero + 1):
if (mask_right & u1) == 0:
if (mask_mask & c1) != 0:
mask_left = mask_left | u1
c1 *= 2
u1 *= 2
joint_mask = mask_left | mask_right
if answer[mask_left] and not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
by_last_one[last_one].append(joint_mask)
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
return False, None, None
def calc_last_one(x):
result = -1
while x > 0:
x = x >> 1
result = result + 1
return result
def build_answer(k, masks, left, right):
c = [-1] * k
p = [-1] * k
pos = (1 << k) - 1
while not masks[pos]:
for i, a, j in masks[right[pos]]:
c[i] = a
p[i] = j
pos = left[pos]
for i, a, j in masks[pos]:
c[i] = a
p[i] = j
return True, c, p
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path.append((i_next, a[i_next][j_next], i))
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
if __name__ == "__main__":
main()
```
No
| 97,080 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n Γ m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input
The first line contains two integer n and m (1 β€ n, m β€ 10^6, 1 β€ n β
m β€ 10^6) β the sizes of the map.
Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
Output
In the first line print the single integer T β the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n Γ m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
Examples
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
Submitted Solution:
```
import os, sys, math
import collections
#res = solve('(R' + ('(R)R' * 2) + ')')
if os.path.exists('testing'):
name = os.path.basename(__file__)
if name.endswith('.py'):
name = name[:-3]
src = open(name + '.in.txt', encoding='utf8')
input = src.readline
sy, sx = map(int, input().strip().split())
data = [
[0] * (sx + 2)
]
for y in range(0, sy):
data.append([0] + [ 1 if q == 'X' else 0 for q in input().strip() ] + [0])
data.append([0] * (sx + 2))
def print_data():
return
for y in data:
print(''.join(map(str, y)))
def solve():
ranges_h = [ [ (x, x) for x in range(sx + 2) ] for _ in range(sy + 2) ]
ranges_w = [ [ (y, y) for _ in range(sx + 2) ] for y in range(sy + 2) ]
colcount = [ 0 ] * (sx + 2)
for y in range(1, sy + 1):
rowcount = 0
for x in range(1, sx + 1):
if data[y][x]:
colcount[x] += 1
rowcount += 1
else:
tmp = (y - colcount[x], y - 1)
for yy in range(y - colcount[x], y):
ranges_h[yy][x] = tmp
tmp = (x - rowcount, x - 1)
for xx in range(x - rowcount, x):
ranges_w[y][xx] = tmp
rowcount = 0
colcount[x] = 0
else:
x += 1
tmp = (x - rowcount, x)
for xx in range(x - rowcount, x):
ranges_w[y][xx] = (x - rowcount, x)
else:
y += 1
for x in range(1, sx + 1):
tmp = (y - colcount[x], y - 1)
for yy in range(y - colcount[x], y):
ranges_h[yy][x] = tmp
def calc_r_w(x, y, dx):
rw = ranges_w[y][x]
if dx < 0:
rw = x - rw[0]
else:
rw = rw[1] - x
return rw
def calc_r_h(x, y, dy):
rh = ranges_h[y][x]
if dy < 0:
rh = y - rh[0]
else:
rh = rh[1] - y
return rh
max_T = 99999999
found = None
print_data()
def calc_dxdyr(x, y):
max_r = 0
mdx = mdy = None
for dx, dy in ((-1, -1), (-1, 1), (1, -1), (1, 1)):
min_r_w = calc_r_w(x, y, dx)
min_r_h = calc_r_h(x, y, dy)
r = 1
while True:
min_r_w2 = calc_r_w(x, y + dy * r, dx)
min_r_h2 = calc_r_h(x + dx * r, y, dy)
min_r_w = min(min_r_w, min_r_w2)
min_r_h = min(min_r_h, min_r_h2)
if min_r_w <= r or min_r_h <= r:
break
r += 1
if r > max_r:
max_r = r
mdx = dx
mdy = dy
return max_r, mdx, mdy
for y in range(1, sy + 1):
for x in range(1, sx + 1):
if data[y][x] != 1:
continue
for dx, dy in ((-1, -1), (-1, 1), (1, -1), (1, 1)):
if data[y - dy][x - dx] == 0 and data[y - dy][x] == 0 and data[y][x - dx] == 0:
break
else:
continue
min_r_w = calc_r_w(x, y, dx)
min_r_h = calc_r_h(x, y, dy)
r = 1
while True:
min_r_w2 = calc_r_w(x, y + dy * r, dx)
min_r_h2 = calc_r_h(x + dx * r, y, dy)
min_r_w = min(min_r_w, min_r_w2)
min_r_h = min(min_r_h, min_r_h2)
if min_r_w <= r or min_r_h <= r:
break
r += 1
if r < 2:
max_T = 0
for y in data:
for x in range(len(y)):
if y[x]:
y[x] = 7
print_data()
return 0
max_T = min(max_T, r // 2)
data[y + (r // 2) * dy][x + (r // 2) * dx] = 7
for yy in range(y, y + r * dy + dy, dy):
for xx in range(x, x + r * dx + dx, dx):
data[yy][xx] |= 2
print_data()
return max_T
T = solve()
print(T)
for y in range(1, sy + 1):
print(''.join('X' if data[y][x] == 7 else '.' for x in range(1, sx + 1)))
```
No
| 97,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n Γ m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input
The first line contains two integer n and m (1 β€ n, m β€ 10^6, 1 β€ n β
m β€ 10^6) β the sizes of the map.
Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
Output
In the first line print the single integer T β the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n Γ m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
Examples
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
Submitted Solution:
```
h, w = map(int, input().split())
a = [input() for i in range(h)]
ruiseki = [[0]*(w+1) for i in range(h+1)]
for i in range(h):
for j in range(w):
if a[i][j] == "X":
ruiseki[i+1][j+1] = ruiseki[i+1][j] + 1
else:
ruiseki[i+1][j+1] = ruiseki[i+1][j]
for i in range(h):
for j in range(w):
ruiseki[i+1][j+1] += ruiseki[i][j+1]
def solve(mid):
cnt = 0
num = mid*mid
visited = [[False]*w for i in range(h)]
for i in range(h)[::-1]:
for j in range(w)[::-1]:
if i+mid < h+1 and j+mid < w+1:
res = ruiseki[i+mid][j+mid] + ruiseki[i][j] - ruiseki[i+mid][j] - ruiseki[i][j+mid]
if res == num:
for ii in range(i,i+mid):
for jj in range(j,j+mid):
if visited[ii][jj]:
break
visited[ii][jj] = True
cnt += 1
if ruiseki[h][w] == cnt:
return True
else:
return False
ok = 1
ng = 10**3 + 1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if solve(mid):
ok = mid
else:
ng = mid
ok = (ok-1) // 2
size = (ok*2+1)**2
ans = [["."]*w for i in range(h)]
for i in range(h):
for j in range(w):
ii, jj = i - ok, j - ok
iii, jjj = i + ok, j + ok
if 0 <= ii < h and 0 <= jj < w and 0 <= iii < h and 0 <= jjj < w:
if ruiseki[iii+1][jjj+1] + ruiseki[ii][jj] - ruiseki[iii+1][jj] - ruiseki[ii][jjj+1] == size:
ans[i][j] = "X"
print(ok)
for i in ans:
print("".join(i))
```
No
| 97,082 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n Γ m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input
The first line contains two integer n and m (1 β€ n, m β€ 10^6, 1 β€ n β
m β€ 10^6) β the sizes of the map.
Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
Output
In the first line print the single integer T β the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n Γ m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
Examples
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
Submitted Solution:
```
import os, sys, math
import collections
#res = solve('(R' + ('(R)R' * 2) + ')')
if os.path.exists('testing'):
name = os.path.basename(__file__)
if name.endswith('.py'):
name = name[:-3]
src = open(name + '.in.txt', encoding='utf8')
input = src.readline
sy, sx = map(int, input().strip().split())
data = [
[0] * (sx + 2)
]
for y in range(0, sy):
data.append([0] + [ 1 if q == 'X' else 0 for q in input().strip() ] + [0])
data.append([0] * (sx + 2))
def print_data():
for y in data:
print(''.join(map(str, y)))
def solve():
ranges_h = [ [ (x, x) for x in range(sx + 2) ] for _ in range(sy + 2) ]
ranges_w = [ [ (y, y) for _ in range(sx + 2) ] for y in range(sy + 2) ]
colcount = [ 0 ] * (sx + 2)
for y in range(1, sy + 1):
rowcount = 0
for x in range(1, sx + 1):
if data[y][x]:
colcount[x] += 1
rowcount += 1
else:
tmp = (y - colcount[x], y - 1)
for yy in range(y - colcount[x], y):
ranges_h[yy][x] = tmp
tmp = (x - rowcount, x - 1)
for xx in range(x - rowcount, x):
ranges_w[y][xx] = tmp
rowcount = 0
colcount[x] = 0
else:
x += 1
tmp = (x - rowcount, x - 1)
for xx in range(x - rowcount, x):
ranges_w[y][xx] = tmp
else:
y += 1
for x in range(1, sx + 1):
tmp = (y - colcount[x], y - 1)
for yy in range(y - colcount[x], y):
ranges_h[yy][x] = tmp
max_T = 99999999
for y in range(1, sy + 1):
for x in range(1, sx + 1):
if data[y][x]:
v = ranges_w[y][x]
v = (v[1] - v[0]) // 2
if v < max_T:
max_T = v
v = ranges_h[y][x]
v = (v[1] - v[0]) // 2
if v < max_T:
max_T = v
if max_T > 0:
for y in range(1 + max_T, sy + 1, 1):
rowcount = 0
for x in range(1, sx + 1):
if data[y][x]:
min_h, max_h = ranges_h[y][x]
if min_h + max_T <= y <= max_h - max_T:
rowcount += 1
else:
rowcount = 0
if rowcount > max_T * 2:
data[y][x - max_T] = 2
#print_data()
return max_T
T = solve()
print(T)
for y in range(1, sy + 1):
print(''.join('X' if data[y][x] == 2 else '.' for x in range(1, sx + 1)))
```
No
| 97,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n Γ m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input
The first line contains two integer n and m (1 β€ n, m β€ 10^6, 1 β€ n β
m β€ 10^6) β the sizes of the map.
Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
Output
In the first line print the single integer T β the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n Γ m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
Examples
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
Submitted Solution:
```
n,m = map(int,input().split())
A = ['.' + input()+'.' for i in range(n)]
A = ['.' *(m+2)] + A +['.'*(m+2)]
B = dict()
Res = set()
for i in range(n+2):
for j in range(m+2):
if A[i][j] == 'X':
if A[i+1][j] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i+1,j)]
else:
B[(i,j)].append((i+1,j))
if A[i+1][j+1] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i+1,j+1)]
else:
B[(i,j)].append((i+1,j+1))
if A[i+1][j-1] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i+1,j-1)]
else:
B[(i,j)].append((i+1,j-1))
if A[i][j+1] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i,j+1)]
else:
B[(i,j)].append((i,j+1))
if A[i][j-1] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i,j-1)]
else:
B[(i,j)].append((i,j-1))
if A[i-1][j+1] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i-1,j+1)]
else:
B[(i,j)].append((i-1,j+1))
if A[i-1][j] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i-1,j)]
else:
B[(i,j)].append((i-1,j))
if A[i-1][j-1] == 'X':
if (i,j) not in B.keys():
B[(i,j)] = [(i-1,j-1)]
else:
B[(i,j)].append((i-1,j-1))
T = [[0 for i in range((m+2))]for j in range(n+2)]
que = []
for i in range(n+2):
for j in range(m+2):
if A[i][j] == 'X':
if len(B[(i,j)]) < 8:
T[i][j] = 1
que.append((i,j))
while len(que) > 0:
a,b = que.pop(0)
k = 0
for i in B[(a,b)]:
if T[i[0]][i[1]] == 0:
T[i[0]][i[1]] = T[a][b] + 1
k = 1
que.append(i)
if T[i[0]][i[1]] > T[a][b]:
k = 1
if k == 0:
Res.add(i)
print(max([max(i) for i in T])-1)
R = [['.' for i in range((m))]for j in range(n)]
for i in Res:
a,b = i
R[a][b] = 'X'
for i in R:
for j in i:
print(j,end = '')
print('')
```
No
| 97,084 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
def main():
n = int(input())
xx = [int(a) for a in input().split()]
counts = [0] * (n+3)
for x in xx:
counts[x] += 1
cmn = counts
cmx = counts.copy()
mn = 0
skip = 0
for c1, c2, c3 in zip(counts, counts[1:], counts[2:]):
if skip > 0:
skip -= 1
continue
if c1 > 0:
mn +=1
skip = 2
mx = 0
for i in range(len(counts)):
if counts[i] > 1:
counts[i] -= 1
counts[i+1] +=1
for i in range(len(counts)-1, -1, -1):
if counts[i] > 1:
counts[i] -= 1
counts[i-1] += 1
for c in counts:
if c > 0:
mx += 1
print(mn, mx)
if __name__ == "__main__":
main()
```
| 97,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
n=int(input())
x=input().split()
for i in range(n):
x[i]=int(x[i])
x.sort()
if(n==1):print(1,1)
else:
ls=[]
visited=[0 for i in range(n+5)]
count=0
for i in range(n):
if(i==0):
count+=1
if(i==n-1):
ls.append([x[i],count])
visited[x[i]]=1
else:
if(x[i]==x[i-1]):
count+=1
if(i==n-1):
ls.append([x[i],count])
visited[x[i]]=1
else:
ls.append([x[i-1],count])
visited[x[i-1]]=1
count=1
if(i==n-1):
ls.append([x[i],count])
visited[x[i]]=1
count_max=len(ls)
ls.sort()
mark=[0 for i in range(n+5)]
for i in range(len(ls)):
if(ls[i][1]>2):
mark[ls[i][0]-1]=1
mark[ls[i][0]+1]=1
if(visited[ls[i][0]-1]==0 and visited[ls[i][0]+1]==0):
count_max+=2
visited[ls[i][0]-1]=1
visited[ls[i][0]+1]=1
elif(visited[ls[i][0]-1]==0):
count_max+=1
visited[ls[i][0]-1]=1
elif(visited[ls[i][0]+1]==0):
count_max+=1
visited[ls[i][0]+1]=1
elif(ls[i][1]==2):
if(mark[ls[i][0]]==1):
mark[ls[i][0]-1]=1
mark[ls[i][0]+1]=1
if(visited[ls[i][0]-1]==0 and visited[ls[i][0]+1]==0):
count_max+=2
visited[ls[i][0]-1]=1
visited[ls[i][0]+1]=1
elif(visited[ls[i][0]-1]==0):
count_max+=1
visited[ls[i][0]-1]=1
elif(visited[ls[i][0]+1]==0):
count_max+=1
visited[ls[i][0]+1]=1
else:
if(visited[ls[i][0]-1]==0):
count_max+=1
visited[ls[i][0]-1]=1
mark[ls[i][0]-1]=1
elif(visited[ls[i][0]+1]==0):
count_max+=1
visited[ls[i][0]+1]=1
mark[ls[i][0]+1]=1
else:
mark[ls[i][0]+1]=1
else:
if(mark[ls[i][0]]==1):
if(visited[ls[i][0]-1]==0):
count_max+=1
visited[ls[i][0]-1]=1
mark[ls[i][0]-1]=1
elif(visited[ls[i][0]+1]==0):
count_max+=1
visited[ls[i][0]+1]=1
mark[ls[i][0]+1]=1
else:
mark[ls[i][0]+1]=1
else:
if(visited[ls[i][0]-1]==0):
visited[ls[i][0]-1]=1
visited[ls[i][0]]=0
ls=[]
visited=[0 for i in range(n+5)]
count=0
for i in range(n):
if(i==0):
count+=1
if(i==n-1):
ls.append([x[i],count])
visited[x[i]]=1
else:
if(x[i]==x[i-1]):
count+=1
if(i==n-1):
ls.append([x[i],count])
visited[x[i]]=1
else:
ls.append([x[i-1],count])
visited[x[i-1]]=1
count=1
if(i==n-1):
ls.append([x[i],count])
visited[x[i]]=1
count_min=len(ls)
ls.sort()
mark=[0 for i in range(n+5)]
for i in range(len(ls)):
if(visited[ls[i][0]-1]==1 and mark[ls[i][0]]==0):
count_min-=1
mark[ls[i][0]-1]=1
visited[ls[i][0]]=0
elif(visited[ls[i][0]+1]==1 and mark[ls[i][0]]==0):
count_min-=1
mark[ls[i][0]+1]=1
visited[ls[i][0]]=0
elif(mark[ls[i][0]]==0):
mark[ls[i][0]+1]=1
visited[ls[i][0]]=0
visited[ls[i][0]+1]=1
print(count_min,count_max)
```
| 97,086 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
n = int(input())
a_max, a_min = [0]*(n+10), [0]*(n+10)
for x in (map(int, input().split())):
a_max[x] += 1
a_min[x] += 1
ans_min = 0
for i in range(1, n+2):
if a_max[i] and a_max[i-1] == 0:
a_max[i-1] = 1
a_max[i] -= 1
if a_min[i-1]:
a_min[i-1] = a_min[i] = a_min[i+1] = 0
ans_min += 1
for i in range(n, -1, -1):
if a_max[i] and a_max[i+1] == 0:
a_max[i+1] = 1
a_max[i] -= 1
for i in range(1, n+1):
if a_max[i] > 1:
a_max[i] = 1
print(ans_min, sum(a_max))
```
| 97,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
n = int( input() )
arr = list( map(int, input().split()) )
vis = [0] * (n + 2)
frec = [0] * (n + 2)
for x in arr:
frec[x] += 1
arr.sort()
mx = 0
for x in arr:
if vis[x-1]==0:
mx += 1
vis[x-1] = 1
elif vis[x]==0:
mx += 1
vis[x] = 1
elif vis[x+1]==0:
mx += 1
vis[x+1] = 1
l, r = 2, n-1
mn_l = 0
mn_r = 0
while l <= n + 1:
if frec[l-1]:
mn_l += 1
l += 2
l += 1
while r >= 0:
if frec[r+1]:
mn_r += 1
r -= 2
r -= 1
print(min(mn_l, mn_r) , mx)
```
| 97,088 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
import heapq
n, = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a.sort()
ans = [0, 0]
last0 = None
last1 = None
for x in a:
if last0 == None or x - 1 > last0:
last0 = x + 1
ans[0] += 1
if last1 == None or x - 1 > last1 + 1:
last1 = x - 1
ans[1] += 1
elif x - 1 <= last1 + 1 <= x + 1:
last1 = last1 + 1
ans[1] += 1
print(ans[0], ans[1])
```
| 97,089 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
n=int(input())
arr=list(map(int,input().split()))
v=[0]*200005
for i in arr:
v[i]+=1
p1=-1
p2=-1
l=0
h=0
for i in range(1,n+1):
if v[i] and p1<i-1:
l+=1
p1=i+1
if v[i] and p2<i-1:
h+=1
p2=i-1
v[i]-=1
if v[i] and p2<i:
h+=1
p2=i
v[i]-=1
if v[i] and p2<i+1:
h+=1
p2=i+1
v[i]-=1
print(l,h)
```
| 97,090 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
import string
from collections import defaultdict,Counter
from math import sqrt, log10, log2, log, gcd, ceil, floor,factorial
from bisect import bisect_left, bisect_right
from itertools import permutations,combinations_with_replacement
import sys,io,os;
input=sys.stdin.readline
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# print=sys.stdout.write
sys.setrecursionlimit(10000)
mod=int(pow(10,7)+9)
inf = float('inf')
def get_list():
return [int(i) for i in input().split()]
def yn(a):
print("YES" if a else "NO",flush=False)
t=1
for i in range(t):
n=int(input())
l=get_list()
l.sort()
seta2=set()
for i in l:
for j in range(i-1,i+2):
if j not in seta2:
seta2.add(j)
break;
l=sorted(set(l))
dict=defaultdict(int)
for i in l:
dict[i]=1
counter=0
for i in range(len(l)):
if i != len(l) - 1:
if dict[l[i]] and dict[l[i + 1]]:
if l[i] + 2 == l[i + 1]:
dict[l[i]] = 0
dict[l[i + 1]] = 0
counter += 1
if i<len(l)-2:
if dict[l[i]] and dict[l[i+1]] and dict[l[i+2]]:
if l[i]+1==l[i+1]==l[i+2]-1:
dict[l[i]]=0
dict[l[i+2]]=0
if i!=len(l)-1:
if dict[l[i]] and dict[l[i+1]]:
if l[i] + 1 == l[i + 1]:
dict[l[i + 1]] = 0
for i in range(len(l)-1):
if dict[l[i]] and dict[l[i+1]]:
if l[i]+1==l[i+1]:
dict[l[i+1]]=0
# print(dict)
print(counter+sum([dict[i] for i in l]),len(seta2))
"""
5
1 3 4 5 6
output: 2 5 (1 3 ) and (4 5 6)
6
1 2 3 5 6 7
output: 2 6
5
1 2 4 5 6
output: 2 5
5
1 3 5 6 7
output 2 5
"""
```
| 97,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Tags: dp, greedy
Correct Solution:
```
n = int(input())
l = list(map(int, input().split()))
l1 = [0] * n
for i in range(n):
l1[i] = l[i]
l.sort()
l1 = list(set(l1))
l1.sort()
ans1 = 0
tem = l1[0]
for i in range(len(l1)):
if l1[i] - tem > 2:
ans1 -= -1
tem = l1[i]
ans1 -= -1
for i in range(n):
if i - 1 >= 0:
if l[i] - 1 != l[i - 1]:
l[i] = l[i] - 1
else:
if i + 1 <= n - 1:
if l[i + 1] < l[i]:
l[i], l[i + 1] = l[i + 1], l[i]
if l[i + 1] == l[i]:
l[i + 1] = l[i] + 1
else: l[i] = l[i] - 1
l = list(set(l))
ans2 = len(l)
print(ans1, ans2)
```
| 97,092 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
n = int(input())
a = list(map(int, input().split()))
cnt = [0] * (n + 2)
vis1 = [0] * (n + 2)
vis2 = [0] * (n + 2)
for i in a:
cnt[i] += 1
mn, mx = 0, 0
for i in range(1, n + 1):
if (cnt[i] == 0):
continue
if (vis1[i - 1] == 0 and vis1[i] == 0):
vis1[i + 1] = 1
mn += 1
for k in range(3):
if (vis2[i + k - 1] == 0 and cnt[i] > 0):
mx += 1
vis2[i + k - 1] = 1;
cnt[i] -= 1
print(mn, mx)
```
Yes
| 97,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
a=[int(x) for x in input().split()]
a.sort()
d={}
for i in range(n):
if a[i]-1 not in d:
if a[i] not in d:
d[a[i]+1]=1
else:
d[a[i]]=1
else:
d[a[i]-1]=1
mini=len(d)
d={}
for i in range(len(a)):
if a[i]-1 in d and a[i] in d:
d[a[i]+1]=1
elif a[i]-1 not in d:
d[a[i]-1]=1
else:
d[a[i]]=1
print(mini,len(d))
```
Yes
| 97,094 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
#Ashish Sagar
q=1
for _ in range(q):
n=int(input())
l=list(map(int,input().split()))
a=l
arr=[0]*(2*(10**5)+1)
for i in range(n):
arr[l[i]]+=1
#for maximum
i=1
while(i<2*(10**5)):
if arr[i]==1:
if arr[i-1]==0:
arr[i-1]=1
arr[i]=0
i+=1
elif arr[i]==2 :
if arr[i-1]==0:
arr[i-1]=1
i+=1
else:
arr[i+1]+=1
i+=1
elif arr[i]>2:
arr[i-1]+=1
arr[i+1]+=1
i+=1
else:
i+=1
ans_max=0
for i in range(2*(10**5)+1):
if arr[i]!=0:
ans_max+=1
a.sort()
min=1
a=list(set(a))
a[0]+=1
for i in range(1,len(a)):
if a[i]==a[i-1]:
a[i]=a[i-1]
elif(a[i]-1==a[i-1]):
a[i]=a[i-1]
else:
min+=1
a[i]+=1
if n==200000 :
if ans_max==169701:
print(min,169702)
elif ans_max==170057:
print(min,170058)
else:
print(min,ans_max)
else:
print(min,ans_max)
```
Yes
| 97,095 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
#t=int(input())
for _ in range (t):
n=int(input())
#n,a,b=map(int,input().split())
a=list(map(int,input().split()))
#tp=list(map(int,input().split()))
#s=input()
#n=len(s)
a.sort()
dp=[0]*(n+2)
b=list(set(a))
for i in b:
if dp[i-1]:
dp[i-1]+=1
elif dp[i]:
dp[i]+=1
else:
dp[i+1]+=1
mn=0
for i in dp:
if i:
mn+=1
dp=[0]*(n+2)
for i in a:
if not dp[i-1]:
dp[i-1]+=1
elif dp[i]:
dp[i+1]+=1
else:
dp[i]+=1
mx=0
for i in dp:
if i:
mx+=1
print(mn,mx)
```
Yes
| 97,096 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
import string
from collections import defaultdict,Counter
from math import sqrt, log10, log2, log, gcd, ceil, floor,factorial
from bisect import bisect_left, bisect_right
from itertools import permutations,combinations_with_replacement
import sys,io,os;
input=sys.stdin.readline
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# print=sys.stdout.write
sys.setrecursionlimit(10000)
mod=int(pow(10,7)+9)
inf = float('inf')
def get_list():
return [int(i) for i in input().split()]
def yn(a):
print("YES" if a else "NO",flush=False)
t=1
for i in range(t):
n=int(input())
l=get_list()
l.sort()
seta2=set()
for i in l:
for j in range(i-1,i+2):
if j not in seta2:
seta2.add(j)
break;
l=sorted(set(l))
dict=defaultdict(int)
for i in l:
dict[i]=1
counter=0
for i in range(len(l)):
if i!=0 and i!=len(l)-1:
if dict[l[i]] and dict[l[i-1]] and dict[l[i+1]]:
if l[i-1]+1==l[i]==l[i+1]-1:
dict[l[i-1]]=0
dict[l[i+1]]=0
if i!=len(l)-1:
if dict[l[i]] and dict[l[i+1]]:
if l[i]+2==l[i+1]:
dict[l[i]]=0
dict[l[i+1]]=0
counter+=1
for i in range(len(l)-1):
if dict[l[i]] and dict[l[i+1]]:
if l[i]+1==l[i+1]:
dict[l[i+1]]=0
# print(dict)
print(counter+sum([dict[i] for i in l]),len(seta2))
"""
5
1 3 4 5 6
6
1 2 3 5 6 7
"""
```
No
| 97,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split(' ')))
l.sort()
lonly = set(l)
lonly = list(lonly)
i = 0
lenonly = len(lonly)
res1 = 0
while i < lenonly:
if i + 1 < lenonly:
dif = lonly[i + 1] - lonly[i]
if lonly[i + 1] - lonly[i] == 1:
lonly[i] = lonly[i + 1]
i += 1
elif dif == 2:
lonly[i] = lonly[i + 1] = lonly[i] + 1
i += 1
i += 1
lonly = set(lonly)
print(len(lonly),end=" ")
last = -1
l2 = []
for i in l:
if i == last:
last = i + 1
l2.append(last)
else:
if i > last:
if i - 1 != last:
last = i - 1
l2.append(last)
else:
last = i
l2.append(last)
l2 = set(l2)
print(len(l2))
```
No
| 97,098 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 β€ x_i β€ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ n) β the coordinates of the houses of the friends.
Output
Print two integers β the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
a.sort()
b=[0]*(n+2)
for i in a:
b[i]=1
i=1
c=[0]*(n+2)
while i<=n:
# print(i)
if b[i]==1:
if b[i-1]==1:
b[i]=0
elif b[i+1]==1:
i+=1
b[i-1]=0
else:
i+=1
b[i-1]=0
b[i]=1
i+=1
for i in a:
c[i]+=1
i=1
#print(c)
while i<=n:
# print(i)
if c[i]>1:
if c[i-1]==0:
c[i]-=1
c[i-1]+=1
if c[i+1]==0 and c[i]>1:
c[i]-=1
c[i+1]+=1
i+=1
i+=1
#print(c)
print(sum(b),n+2-(c.count(0)))
```
No
| 97,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.