output_description stringlengths 15 956 | submission_id stringlengths 10 10 | status stringclasses 3 values | problem_id stringlengths 6 6 | input_description stringlengths 9 2.55k | attempt stringlengths 1 13.7k | problem_description stringlengths 7 5.24k | samples stringlengths 2 2.72k |
|---|---|---|---|---|---|---|---|
Print the total number of biscuits produced within T + 0.5 seconds after
activation.
* * * | s875322476 | Wrong Answer | p03059 | Input is given from Standard Input in the following format:
A B T | a, b, n = map(int, input().split())
if a < n:
t = int((n + 0.5) / a)
else:
t = 0
print(b * t)
| Statement
A biscuit making machine produces B biscuits at the following moments: A
seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds
after activation.
Find the total number of biscuits produced within T + 0.5 seconds after
activation. | [{"input": "3 5 7", "output": "10\n \n\n * Five biscuits will be produced three seconds after activation.\n * Another five biscuits will be produced six seconds after activation.\n * Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.\n\n* * *"}, {"input": "3 2 9", "output": "6\n \n\n* * *"}, {"input": "20 20 19", "output": "0"}] |
Print the total number of biscuits produced within T + 0.5 seconds after
activation.
* * * | s000549729 | Accepted | p03059 | Input is given from Standard Input in the following format:
A B T | A, B, C = [int(s) for s in input().split()]
print((C // A) * B)
| Statement
A biscuit making machine produces B biscuits at the following moments: A
seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds
after activation.
Find the total number of biscuits produced within T + 0.5 seconds after
activation. | [{"input": "3 5 7", "output": "10\n \n\n * Five biscuits will be produced three seconds after activation.\n * Another five biscuits will be produced six seconds after activation.\n * Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.\n\n* * *"}, {"input": "3 2 9", "output": "6\n \n\n* * *"}, {"input": "20 20 19", "output": "0"}] |
Print the total number of biscuits produced within T + 0.5 seconds after
activation.
* * * | s474745779 | Runtime Error | p03059 | Input is given from Standard Input in the following format:
A B T | a, b, t = list(map(int, input()))
print(t * b // a)
| Statement
A biscuit making machine produces B biscuits at the following moments: A
seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds
after activation.
Find the total number of biscuits produced within T + 0.5 seconds after
activation. | [{"input": "3 5 7", "output": "10\n \n\n * Five biscuits will be produced three seconds after activation.\n * Another five biscuits will be produced six seconds after activation.\n * Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.\n\n* * *"}, {"input": "3 2 9", "output": "6\n \n\n* * *"}, {"input": "20 20 19", "output": "0"}] |
Print the maximum number of friendly pairs.
* * * | s206871778 | Accepted | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | n = int(input())
r = [tuple(map(int, input().split())) for _ in range(n)]
b = [tuple(map(int, input().split())) for _ in range(n)]
r = sorted(r)
b = sorted(b)
for x, y in b:
p, q = -1, -1
for i, j in r:
if i < x and j < y and j > q:
p, q = i, j
if (p, q) in r:
r.remove((p, q))
print(n - len(r))
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s104624021 | Wrong Answer | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | import random
print(random.randint(0, 100000000))
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s817312805 | Wrong Answer | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | n = int(input())
class Cumulative_Sum_2D:
def __init__(self, a):
lai = len(a)
laj = len(a[0])
self.s = [[0] * (laj + 1) for _ in range(lai + 1)]
for i in range(lai):
for j in range(laj):
self.s[i + 1][j + 1] = self.s[i + 1][j] + a[i][j]
for i in range(lai):
for j in range(laj):
self.s[i + 1][j + 1] += self.s[i][j + 1]
def sum(self, li, lj, ri, rj):
s = self.s
return s[ri][rj] - s[li][rj] - s[ri][lj] + s[li][lj]
size = 2 * n + 2
ab = [[0] * size for _ in range(size)]
cd = [[0] * size for _ in range(size)]
ablist = []
cdlist = []
for _ in range(n):
xi, yi = map(int, input().split())
ab[xi][yi] += 1
ablist.append((xi, yi))
for _ in range(n):
xi, yi = map(int, input().split())
cd[xi][yi] += 1
cdlist.append((xi, yi))
csab = Cumulative_Sum_2D(ab)
cscd = Cumulative_Sum_2D(cd)
# import numpy as np
# print(np.array(csab.s))
# print(np.array(cscd.s))
ans = 0
"""
for ci,di in cdlist:
if cscd.sum(0,0,ci+1,di+1) <= csab.sum(0,0,ci+1,di+1):
ans += 1
print(ci,di,cscd.sum(0,0,ci+1,di+1) ,csab.sum(0,0,ci+1,di+1))
print(ans)
"""
ans2 = 0
for ai, bi in cdlist:
if cscd.sum(ai, bi, size, size) == 0:
ans2 += 1
# print(ai,bi,cscd.sum(ai,bi, size, size) , csab.sum(ai,bi, size, size))
print(n - ans2)
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s254551384 | Wrong Answer | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | n = int(input())
red1 = sorted([list(map(int, input().split())) for i in range(n)], key=lambda x: x[1])
blue1 = sorted([list(map(int, input().split())) for i in range(n)], key=lambda x: x[1])
red2 = sorted(red1, key=lambda x: x[0])
blue2 = sorted(blue1, key=lambda x: x[0])
cr1 = [0] * n
cr2 = [0] * n
for i in range(n):
for j in range(n - 1, -1, -1):
if blue1[i][0] > red1[j][0] and blue1[i][1] > red1[j][1] and cr1[j] == 0:
cr1[j] = 1
break
for i in range(n):
for j in range(n - 1, -1, -1):
if blue2[i][0] > red2[j][0] and blue2[i][1] > red2[j][1] and cr2[j] == 0:
cr2[j] = 1
break
# print(cr)
print(max(sum(cr1), sum(cr2)))
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s046385648 | Accepted | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | length = int(input())
lower = []
higher = []
for i in range(length):
x, y = map(int, input().split(" "))
lower.append([x, y])
for i in range(length):
x, y = map(int, input().split(" "))
higher.append([x, y])
match = [set() for n in range(length)]
for high in range(length):
for low in range(length):
high_x, high_y = higher[high][0], higher[high][1]
low_x, low_y = lower[low][0], lower[low][1]
if high_x > low_x and high_y > low_y:
match[high] |= {low}
matched_lower_set = set()
matched_higher_set = set()
def ret_minimum_match(match, lower_i, matched_higher_set, matched_lower_set):
min_i = -1
min_len = 101
for i, ma in enumerate(match):
if i in matched_higher_set or lower_i not in ma:
continue
if min_len > len(ma - matched_lower_set) > 0:
min_len = len(ma - matched_lower_set)
min_i = i
return {min_i}
while True:
lowers = [[] for n in range(length)]
for i, mat in enumerate(match):
if i in matched_higher_set:
continue
for m in mat:
if m not in matched_lower_set:
lowers[m].append(i)
only_one_deleted = 0
# print(lowers, matched_lower_set, matched_higher_set)
for i, lo in enumerate(lowers):
if len(lo) == 1:
matched_higher_set |= ret_minimum_match(
match, i, matched_higher_set, matched_lower_set
)
matched_lower_set |= {i}
only_one_deleted = 1
break
if all([True if len(n) <= 0 else False for n in lowers]):
break
if not only_one_deleted:
min_i, min_len = -1, 101
for i, lo in enumerate(lowers):
if min_len > len(lo) > 0:
min_i = i
min_len = len(lo)
matched_higher_set |= ret_minimum_match(
match, min_i, matched_higher_set, matched_lower_set
)
matched_lower_set |= {min_i}
print(len(matched_lower_set))
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s134185294 | Wrong Answer | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | # coding:utf-8
import sys
# from collections import Counter, defaultdict
INF = float("inf")
MOD = 10**9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LI_():
return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def II():
return int(sys.stdin.readline())
def SI():
return input()
def main():
n = II()
red = [[a + b, a, b] for a, b in (LI() for _ in range(n))]
blue = [[a + b, a, b] for a, b in (LI() for _ in range(n))]
ans = 0
for _ in range(n):
red = red[-1:] + red[:-1]
used = [0] * n
res = 0
for s, a, b in red:
near = -1
d = INF
for i, (ss, x, y) in enumerate(blue):
if a < x and b < y:
tmp = x - a + y - b
if tmp < d and not used[i]:
near = i
d = tmp
if near != -1:
used[near] = 1
res += 1
ans = max(ans, res)
red.reverse()
for _ in range(n):
red = red[-1:] + red[:-1]
used = [0] * n
res = 0
for s, a, b in red:
near = -1
d = INF
for i, (ss, x, y) in enumerate(blue):
if a < x and b < y:
tmp = x - a + y - b
if tmp < d and not used[i]:
near = i
d = tmp
if near != -1:
used[near] = 1
res += 1
ans = max(ans, res)
red.reverse()
red.sort()
for _ in range(n):
red = red[-1:] + red[:-1]
used = [0] * n
res = 0
for s, a, b in red:
near = -1
d = INF
for i, (ss, x, y) in enumerate(blue):
if a < x and b < y:
tmp = x - a + y - b
if tmp < d and not used[i]:
near = i
d = tmp
if near != -1:
used[near] = 1
res += 1
ans = max(ans, res)
red.reverse()
for _ in range(n):
red = red[-1:] + red[:-1]
used = [0] * n
res = 0
for s, a, b in red:
near = -1
d = INF
for i, (ss, x, y) in enumerate(blue):
if a < x and b < y:
tmp = x - a + y - b
if tmp < d and not used[i]:
near = i
d = tmp
if near != -1:
used[near] = 1
res += 1
ans = max(ans, res)
return ans
print(main())
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s910731657 | Wrong Answer | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | def check_rec(bc, rc, pair):
if len(bc) == 0 or len(rc) == 0:
return pair
bcc = bc.copy()
e = bcc.pop()
pairs = [pair]
for i in rc:
if e[0] > i[0] and e[1] > i[1]:
rcc = rc.copy()
rcc.remove(i)
pairs.append(check_rec(bcc, rcc, pair + 1))
return max(pairs)
n = int(input())
rc, bc = set(), set()
for i in range(n):
rc.add(tuple(map(int, input().split())))
for i in range(n):
bc.add(tuple(map(int, input().split())))
print(check_rec(bc, rc, 0))
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s987925825 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | N = int(input())
reds = sorted([list(map(int,input().split()))])
blues = sorted([list(map(int,input().split()))])
reds.sort(reverse = True)
res = 0
for c,d in blues:
for a,b in reds:
if a,c and b<d:
reds.remove([a,b])
res+=1
break
print(res) | Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s786127649 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | # input
N, M = map(int, input().split())
# check
if 2 in [M, N] or N == M == 1:
print(0)
elif 1 in [M, N]:
print(N * M - 2)
else:
print(N * M - (2 * (N + M) - 4))
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s741471594 | Accepted | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | ###############################################################################
from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict
mod = 1
def intin():
input_tuple = input().split()
if len(input_tuple) <= 1:
return int(input_tuple[0])
return tuple(map(int, input_tuple))
def intina():
return [int(i) for i in input().split()]
def intinl(count):
return [intin() for _ in range(count)]
def modadd(x, y):
global mod
return (x + y) % mod
def modmlt(x, y):
global mod
return (x * y) % mod
def lcm(x, y):
while y != 0:
z = x % y
x = y
y = z
return x
def combination(x, y):
assert x >= y
if y > x // 2:
y = x - y
ret = 1
for i in range(0, y):
j = x - i
i = i + 1
ret = ret * j
ret = ret // i
return ret
def get_divisors(x):
retlist = []
for i in range(1, int(x**0.5) + 3):
if x % i == 0:
retlist.append(i)
retlist.append(x // i)
return retlist
def get_factors(x):
retlist = []
for i in range(2, int(x**0.5) + 3):
while x % i == 0:
retlist.append(i)
x = x // i
retlist.append(x)
return retlist
def make_linklist(xylist):
linklist = {}
for a, b in xylist:
linklist.setdefault(a, [])
linklist.setdefault(b, [])
linklist[a].append(b)
linklist[b].append(a)
return linklist
def calc_longest_distance(linklist, v=1):
distance_list = {}
distance_count = 0
distance = 0
vlist_previous = []
vlist = [v]
nodecount = len(linklist)
while distance_count < nodecount:
vlist_next = []
for v in vlist:
distance_list[v] = distance
distance_count += 1
vlist_next.extend(linklist[v])
distance += 1
vlist_to_del = vlist_previous
vlist_previous = vlist
vlist = list(set(vlist_next) - set(vlist_to_del))
max_distance = -1
max_v = None
for v, distance in distance_list.items():
if distance > max_distance:
max_distance = distance
max_v = v
return (max_distance, max_v)
def calc_tree_diameter(linklist, v=1):
_, u = calc_longest_distance(linklist, v)
distance, _ = calc_longest_distance(linklist, u)
return distance
class UnionFind:
def __init__(self, n):
self.parent = [i for i in range(n)]
def root(self, i):
if self.parent[i] == i:
return i
self.parent[i] = self.root(self.parent[i])
return self.parent[i]
def unite(self, i, j):
rooti = self.root(i)
rootj = self.root(j)
if rooti == rootj:
return
if rooti < rootj:
self.parent[rootj] = rooti
else:
self.parent[rooti] = rootj
def same(self, i, j):
return self.root(i) == self.root(j)
###############################################################################
def main():
n = intin()
ablist = intinl(n)
cdlist = intinl(n)
ablist.sort()
cdlist.sort()
ans = 0
while ablist:
a, b = ablist.pop()
idx = binl(cdlist, (a, b))
cand = None
for i, (c, d) in enumerate(cdlist[idx:]):
if b < d:
if cand is None:
cand = (i, c, d)
else:
ci, cc, cd = cand
if d < cd:
cand = (i, c, d)
if cand is None:
continue
ci, cc, cd = cand
del cdlist[idx + ci]
ans += 1
print(ans)
if __name__ == "__main__":
main()
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s703137443 | Wrong Answer | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | # 91c
N = int(input()) # N<=100
red_points = list()
for i in range(N):
a, b = map(int, input().split())
red_points.append((a, b))
blue_points = list()
for i in range(N):
c, d = map(int, input().split())
blue_points.append((c, d))
# 赤い点と青い点は,
# 赤い点の x 座標が青い点の x 座標より小さく, また
# 赤い点の y 座標も青い点の y座標より小さい とき,
# 仲良しペアになれます。
# あなたは最大で何個の仲良しペアを作ることができますか? ただし,1つの点が複数のペアに所属することはできません。
# 100*100 = 10**4ループを回して、ペアになれる点同士を算出
pairable_dict = dict() # key:red_point , value:pairable blue point
for red_point in red_points:
pairable_dict[red_point] = set()
red_point_x = red_point[0]
red_point_y = red_point[1]
for blue_point in blue_points:
blue_point_x = blue_point[0]
blue_point_y = blue_point[1]
if red_point_x < blue_point_x and red_point_y < blue_point_y:
pairable_dict[red_point].add(blue_point)
# print(pairable_dict)
pair_dict = dict() # key:red_point , value:paired blue point
used_blue_points = set()
# ペアになれる相手が単独なら確定していく
def make_unique_pair():
for pair in pairable_dict.items():
red_point = pair[0]
blue_points = pair[1]
blue_points = blue_points - (blue_points & used_blue_points)
# print(red_point,blue_points)
if len(blue_points) == 1:
# print("paired")
blue_point = blue_points.pop()
pair_dict[red_point] = blue_point
used_blue_points.add(blue_point)
pairable_dict[red_point] = set()
make_unique_pair()
# 単独ペア確定後は、近い点からやっていく
def make_pair():
for pair in pairable_dict.items():
red_point = pair[0]
blue_points = pair[1]
blue_points = blue_points - (blue_points & used_blue_points)
if len(blue_points) != 0:
# 最も近い点を使う
min_d_point = blue_points.pop()
min_distance = min_d_point[0] ** 2 + min_d_point[1] ** 2
for blue_point in blue_points:
if blue_point[0] ** 2 + blue_point[1] ** 2 < min_distance:
min_distance = blue_point[0] ** 2 + blue_point[1] ** 2
min_d_point = blue_point
pair_dict[red_point] = min_d_point
used_blue_points.add(min_d_point)
pairable_dict[red_point] = set()
make_pair()
make_unique_pair()
make_pair()
print(len(pair_dict))
# print(pair_dict)
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s879196215 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | z
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s758822637 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NEW(p,n){p=malloc((n)*sizeof(p[0]));if(p==NULL){printf("not enough memory\n");exit(1);};}
//pの型の変数n個の要素分のメモリを確保し、そのアドレスをpに代入するマクロ
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define SWAP(type, x, y) do { type tmp = x; x = y; y = tmp; } while (0)
#define MOD 1000000007
typedef struct{
int x;
int y;
int flg;
}data;
//x軸の昇順
int xasc(const void* a, const void* b){
data p = *(data*)a;
data q = *(data*)b;
if(p.x!=q.x) return p.x-q.x;
else return p.y-q.y;
}
//y軸の降順
int ydesc(const void* a, const void* b){
data p = *(data*)a;
data q = *(data*)b;
if(p.y!=q.y) return q.y-p.y;
else return q.x-p.x;
}
int main(void){
int N;
scanf("%d",&N);
//A[0]~A[N-1]に格納する
data* red;
NEW(red,N);
for(int i=0;i<N;i++){
scanf("%d%d",&red[i].x,&red[i].y);
red[i].flg=0;
}
qsort(red,N,sizeof(data),ydesc);
data* blue;
NEW(blue,N);
for(int i=0;i<N;i++){
scanf("%d%d",&blue[i].x,&blue[i].y);
blue[i].flg=0;
}
qsort(blue,N,sizeof(data),xasc);
int ans=0;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(red[j].flg) continue;
if(red[j].x<blue[i].x && red[j].y<blue[i].y){
ans++;
red[j].flg=1;
break;
}
}
}
printf("%d\n",ans);
return 0;
} | Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s273801578 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | ■標準入力ショートカット
def get_next_int():
return int(float(input()))
def get_next_ints(delim=" "):
return tuple([int(float(x)) for x in input().split(delim)])
def get_next_str():
return input()
def get_next_strs(delim=" "):
return tuple(input().split(delim))
def get_next_by_types(*value_types, delim=" "):
return tuple([t(x) for t, x in zip(value_types, input().split(delim))])
import heapq
def solve():
N = get_next_int()
red_heap = []
for i in range(N):
a, b = get_next_ints()
heapq.heappush(red_heap, (b, a))
blue_heap = []
for i in range(N):
c, d = get_next_ints()
heapq.heappush(blue_heap, (d, c))
blue_heap = sorted(blue_heap)
red_heap = sorted(red_heap)
ans = 0
while(len(blue_heap) > 0):
blue_pos = heapq.heappop(blue_heap)
for i in range(len(red_heap)):
red_pos = red_heap[i]
if blue_pos[0] > red_pos[0] and blue_pos[1] > red_pos[1]:
ans += 1
del red_heap[i]
break
elif blue_pos[0] < red_pos[0]:
break
print(ans)
solve() | Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s005395337 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | import sys
import copy
if sys.platform =='ios':
sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def MAP(): return [int(s) for s in input().split()]
N = int(input())
A = [[False,MAP()] for _ in range(N)]
B = [[False,MAP()] for _ in range(N)]
#print(sorted(B))
#below is incorrect
#count = 0
#for b in B:
# delta = []
# for a in A:
# delta.append([a,[b[1][0] - a[1][0], b[1][1] - a[1][1]]])
#print(b,delta)
# cand = [[d[1][0]+d[1][1],d[0][1]] for d in delta if not d[0][0] and d[1][0] > 0 and d[1][1] > 0]
# if cand:
# cand = sorted(cand)
# print(cand)
# b[0] = True
# A[A.index([False,cand[0][1]])][0] = True
# count += 1
#after reading answer
count = 0
for b in B:
cand = []
for a in A:
if b[1][0] > a[1][0] and b[1][1] > a[1][1] not a[0]:
cand.append(a)
cand = sorted(cand, key=lambda x:x[1][1], reverse=True)
if cand:
#print(b, cand[0])
b[0] = True
cand[0][0] = True
count += 1
print(count) | Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s051208225 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | N = int(input())
R = [list(map(int, input().split(" "))) for _ in range(N)]
B = [list(map(int, input().split(" "))) for _ in range(N)]
R.sort(key=lambda x: (x[1], x[0]), reverse=True)
B.sort(key=lambda x: (x[0], x[1]))
f = [0] * N
print(R)
print(B)
pair = 0
for b in B:
for i, r in enumerate(R):
if r[0] < b[0] and r[1] < b[1] and f[i] == 0:
print(r[0],r[1],b[0],b[1])
pair += 1
f[i] = 1
break
print(pair) | Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
Print the maximum number of friendly pairs.
* * * | s283643218 | Runtime Error | p03409 | Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N | n = int(input())
a = []
b = []
c = []
d = []
for i in range(0,2n):
a.append(str(input()).split())
for i in range(0,n):
d.append(0)
for i in range(0,n):
for j in range(n,2n):
if int(a[i][0]) < int(a[j][0]) and int(a[i][1]) < int(a[j]):
b.append(1)
else:
b.append(0)
if i == n-1:
c.append(b)
sum = []
for I in range(0,n+1):
sum.append(0)
answer = 0
for i in range(0,n):
for j in range(0,n):
if c[i][j] == 1:
d[j] = 1
if j == n-1:
for k in range(0,n):
sum[i+1] += d[k]
if sum[i] >= sum[i-1]:
answer += 1
print(answer)
| Statement
On a two-dimensional plane, there are N red points and N blue points. The
coordinates of the i-th red point are (a_i, b_i), and the coordinates of the
i-th blue point are (c_i, d_i).
A red point and a blue point can form a _friendly pair_ when, the x-coordinate
of the red point is smaller than that of the blue point, and the y-coordinate
of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong
to multiple pairs. | [{"input": "3\n 2 0\n 3 1\n 1 3\n 4 2\n 0 4\n 5 5", "output": "2\n \n\nFor example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).\n\n* * *"}, {"input": "3\n 0 0\n 1 1\n 5 2\n 2 3\n 3 4\n 4 5", "output": "2\n \n\nFor example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).\n\n* * *"}, {"input": "2\n 2 2\n 3 3\n 0 0\n 1 1", "output": "0\n \n\nIt is possible that no pair can be formed.\n\n* * *"}, {"input": "5\n 0 0\n 7 3\n 2 2\n 4 8\n 1 6\n 8 5\n 6 9\n 5 4\n 9 1\n 3 7", "output": "5\n \n\n* * *"}, {"input": "5\n 0 0\n 1 1\n 5 5\n 6 6\n 7 7\n 2 2\n 3 3\n 4 4\n 8 8\n 9 9", "output": "4"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s433169178 | Runtime Error | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | N = int(input())
VW = [list(map(int, input().split())) for _ in range(N)]
Q = int(input())
vL = [list(map(int, input().split())) for _ in range(Q)]
for vLi in vL:
vi = vLi[0]
Li = vLi[1]
vw = VW[vi - 1]
stock = [(vw[0], vw[1])]
while vi != 1:
vi = vi // 2
vw = VW[vi - 1]
stock.append((vw[0], vw[1]))
V = [0 for _ in range(Li + 1)]
for vi, wi in stock[:-1]:
for l in range(1, Li + 1)[::-1]:
if l >= wi:
V[l] = max(V[l], V[l - wi] + vi)
else:
V[l] = V[l]
vi = stock[-1][0]
wi = stock[-1][1]
print(max(V[Li], V[Li - wi] + vi))
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s798759305 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys, bisect
input = sys.stdin.readline
N = int(input())
vw = [(-1, -1)]
for i in range(N):
vw.append(tuple(map(int, input().split())))
dp1 = [[0, 0] for i in range(2**9)]
dp2 = [[0, 0] for i in range(2**9)]
for _ in range(int(input())):
v, l = map(int, input().split())
t = []
while v > 0:
t.append(vw[v])
v //= 2
dp1 = [[0, 0] for i in range(2**9)]
dp2 = [[0, 0] for i in range(2**9)]
n = len(t)
dp1[0][0] = 0
dp1[0][1] = 0
k = n // 2
for i in range(1, 2**k):
m = i.bit_length()
dp1[i][0] = dp1[i - 2 ** (m - 1)][0] + t[m - 1][1]
dp1[i][1] = dp1[i - 2 ** (m - 1)][1] + t[m - 1][0]
dp2[0][0] = 0
dp2[0][1] = 0
for i in range(1, 2 ** (n - k)):
m = i.bit_length()
dp2[i][0] = dp2[i - 2 ** (m - 1)][0] + t[m - 1 + k][1]
dp2[i][1] = dp2[i - 2 ** (m - 1)][1] + t[m - 1 + k][0]
dp1.sort()
dp2.sort()
ans = 0
for i in range(0, 2**9):
res = dp1[i][1]
id = bisect.bisect_right(dp2, [l - dp1[i][0], 10**20])
if id != 0:
res += dp2[id - 1][1]
ans = max(ans, res)
print("ANS")
print(ans)
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s227248650 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys
import numpy as np
from numba import njit
@njit("i8[:](i8,i8[:],i8[:],i8,i8[:],i8[:])", cache=True)
def solve(n, vvv, www, q, uuu, lll):
weight_limit = 10**5
precalc_limit = min(1 << 9, n + 1)
precalc = np.zeros((precalc_limit, weight_limit + 1), dtype=np.int64)
for u in range(1, precalc_limit):
v = vvv[u]
w = www[u]
p = u >> 1
precalc[u, :w] = precalc[p, :w]
precalc[u, w:] = np.maximum(precalc[p, w:], precalc[p, :-w] + v)
buf = np.zeros(q, dtype=np.int64)
for i in range(q):
u = uuu[i]
l = lll[i]
if u < precalc_limit:
buf[i] = precalc[u, l]
continue
dp = {0: 0}
while u >= precalc_limit:
v = vvv[u]
w = www[u]
for cw, cv in list(dp.items()):
nw = cw + w
nv = cv + v
if nw > weight_limit:
continue
if nw not in dp or dp[nw] < nv:
dp[nw] = nv
u >>= 1
ans = 0
for w, v in dp.items():
ans = max(ans, v + precalc[u, l - w])
buf[i] = ans
return buf
n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = np.array([0] + inp[0 : n * 2 : 2], dtype=np.int64)
www = np.array([0] + inp[1 : n * 2 : 2], dtype=np.int64)
q = inp[n * 2]
uuu = np.array(inp[n * 2 + 1 :: 2], dtype=np.int64)
lll = np.array(inp[n * 2 + 2 :: 2], dtype=np.int64)
ans = solve(n, vvv, www, q, uuu, lll)
print("\n".join(map(str, ans)))
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s087681371 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import bisect
import os
from collections import defaultdict
import itertools
import sys
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10**9)
INF = float("inf")
IINF = 10**18
MOD = 10**9 + 7
# MOD = 998244353
# ガウス記号!おぼえた
N = int(sys.stdin.buffer.readline())
VW = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
Q = int(sys.stdin.buffer.readline())
VL = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]
VW = [(0, 0)] + VW
D = N.bit_length()
queries = defaultdict(list)
for i, (v, l) in enumerate(VL):
queries[v].append((l, i))
ans = [-1] * Q
def solve(wv, i):
# print(wv,i)
if not queries[i]:
return
wv1 = []
prev_v = -INF
for w, v in sorted(wv):
v = max(prev_v, v)
wv1.append((w, v))
prev_v = v
wva = []
for j in range(len(wv).bit_length() - i.bit_length()):
wva.append((VW[i >> j][1], VW[i >> j][0]))
wv = []
for choices in itertools.product([True, False], repeat=len(wva)):
ws, vs = 0, 0
for j, (w, v) in enumerate(wva):
if choices[j]:
ws += w
vs += v
wv.append((ws, vs))
wv2 = []
prev_v = -INF
for w, v in sorted(wv):
v = max(prev_v, v)
wv2.append((w, v))
prev_v = v
for ql, qi in queries[i]:
ret = 0
for w2, v2 in wv2:
idx = bisect.bisect_left(wv1, (ql - w2 + 1, -INF)) - 1
if idx >= 0:
ret = max(ret, wv1[idx][1] + v2)
ans[qi] = ret
def dfs(d, wv, p):
if p > N:
return
solve(wv, p)
for i in (p << 1, (p << 1) + 1):
if i > N:
break
if d <= MAX_D:
next_wv = []
for w, v in wv:
next_wv.append((w + VW[i][1], v + VW[i][0]))
dfs(d + 1, wv + next_wv, i)
else:
dfs(d + 1, wv, i)
MAX_D = 9
dfs(1, [(0, 0), (VW[1][1], VW[1][0])], 1)
print(*ans, sep="\n")
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s930079389 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys
input = sys.stdin.buffer.readline
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
half_n = 2 ** (n.bit_length() // 2)
tot1 = [[] for i in range(n)]
tot1[0].append((0, 0))
tot1[0].append((info[0][1], info[0][0]))
for i in range(1, half_n):
val, wei = info[i]
for w, v in tot1[(i + 1) // 2 - 1]:
tot1[i].append((w, v))
tot1[i].append((w + wei, v + val))
tot1[i].sort()
for i in range(half_n, n):
if (i + 1) // 2 - 1 < half_n:
tot1[i].append((info[i][1], info[i][0]))
tot1[i].append((0, 0))
else:
val, wei = info[i]
for w, v in tot1[(i + 1) // 2 - 1]:
tot1[i].append((w, v))
tot1[i].append((w + wei, v + val))
tot1[i].sort(reverse=True)
for i, l in query:
i -= 1
ans = 0
if i < half_n:
for w, v in tot1[i]:
if w <= l:
ans = max(ans, v)
print(ans)
else:
ind = i + 1
while ind > half_n:
ind //= 2
ind -= 1
max_ = 0
left = 0
for w, v in tot1[i]:
while left < len(tot1[ind]):
w2, v2 = tot1[ind][left]
if w2 + w > l:
break
max_ = max(max_, v2)
left += 1
ans = max(max_ + v, ans)
print(ans)
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s613461555 | Runtime Error | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | N = int(input())
V = [0]
W = [0]
for _ in range(N):
tmp1, tmp2 = map(int, input().split())
V.append(tmp1)
W.append(tmp2)
Q = int(input())
v = []
L = []
for _ in range(N):
tmp1, tmp2 = map(int, input().split())
v.append(tmp1)
L.append(tmp2)
# v_は今いる場所
def explorer(V_, W_, v_, L_):
if v_ == 1:
if W_ + W[1] <= L_:
return V_ + V[1]
else:
return V_
elif W_ + W[v_] <= L_:
return max(
explorer(V_ + V[v_], W_ + W[v_], v_ // 2, L_), explorer(V_, W_, v_ // 2, L_)
)
else:
return explorer(V_, W_, v_ // 2, L_)
for i in range(len(L)):
print(explorer(0, 0, v[i], L[i]))
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s616650216 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | 1
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s889440304 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | def main():
from sys import stdin
input = stdin.readline
n = int(input())
vw = [list(map(int, input().split())) for _ in [0] * n]
q = int(input())
vl = [list(map(int, input().split())) for _ in [0] * q]
former = min(512, n)
former_dp = [[-1] * 100001 for _ in [0] * former]
former_set = [set() for _ in [0] * former]
former_dp[0][0] = 0
former_dp[0][vw[0][1]] = vw[0][0]
former_set[0] = {0, vw[0][1]}
for i in range(1, former):
v, w = vw[i]
anc_dp = former_dp[(i - 1) // 2]
now_dp = former_dp[i]
anc_set = former_set[(i - 1) // 2]
now_set = former_set[i]
for j in anc_set:
now_dp[j] = anc_dp[j]
now_set.add(j)
for j in anc_set:
if w + j <= 100000:
now_dp[w + j] = max(now_dp[w + j], anc_dp[j] + v)
now_set.add(w + j)
for i in range(former):
m = 0
now_dp = former_dp[i]
for j in range(1, 100001):
m = max(m, now_dp[j])
now_dp[j] = m
for v, l in vl:
if v <= former:
print(former_dp[v - 1][l])
continue
later = []
vv = v
while vv > former:
later.append(vw[vv - 1])
vv >>= 1
anc_dp = former_dp[vv - 1]
m = len(later)
ans = 0
print(ans)
main()
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s221316616 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | # -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62 - 1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def read_float():
return float(buff_readline())
def read_float_n():
return list(map(float, buff_readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, "sec")
return ret
return wrap
@mt
def slv(N, VW, Q, VL):
V = [0] + [v for v, w in VW]
W = [0] + [w for v, w in VW]
from collections import Counter
from functools import lru_cache
L = 10**5
@lru_cache(maxsize=None)
def g(u):
if u == 1:
memo = Counter()
memo[0] = 0
if W[u] < L:
memo[W[u]] = V[u]
return memo
memo = g(u // 2)
nm = Counter()
for w, v in memo.items():
if w + W[u] <= L:
nm[w + W[u]] = max(nm[w + W[u]], v + V[u])
nm[w] = max(nm[w], v)
return nm
def f(u, l):
m = g(u)
ans = 0
for k in sorted(m.keys()):
if k > l:
break
ans = max(ans, m[k])
return ans
ans = []
for v, l in VL:
ans.append(f(v, l))
return ans
def main():
N = read_int()
VW = [read_int_n() for _ in range(N)]
Q = read_int()
VL = [read_int_n() for _ in range(Q)]
print(*slv(N, VW, Q, VL), sep="\n")
# from random import randint
# N = 2**18
# Q = 10**5
# VW = [[randint(1, 10**5), randint(1, 100)] for _ in range(N)]
# VL = [[i, 10**5] for i in range(1, Q+1)]
# # print(N)
# print(*slv(N, VW, Q, VL), sep='\n')
if __name__ == "__main__":
main()
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s566613256 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
import numpy as np
def main():
n = int(input())
l = [list(map(int, input().split())) for i in range(n)]
dic = {}
q = int(input())
Q = []
lm = 0
for i in range(q):
a, b = map(int, input().split())
lm = max(b, lm)
Q.append((a, b))
d = np.zeros(lm + 1, dtype=np.int64)
if l[0][1] <= lm:
d[l[0][1]] = l[0][0]
dic[1] = d
def dfs(x):
if x in dic:
return dic[x]
v, w = l[x - 1]
li = dfs(x // 2)
d = np.zeros(lm + 1, dtype=np.int64)
d[w:] = np.maximum(li[w:], li[:-w] + v, out=li[w:])
dic[x] = d
return d
for a, b in Q:
s = dfs(a)
print(np.max(s[: b + 1]))
if __name__ == "__main__":
main()
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s740925776 | Wrong Answer | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys
from collections import defaultdict
n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0 : n * 2 : 2]
www = [0] + inp[1 : n * 2 : 2]
mp = iter(inp[n * 2 + 1 :])
query_ls = defaultdict(list)
query_idx = {}
required = [-1] * (n + 1)
for i, q in enumerate(zip(mp, mp)):
query_idx[q] = i
u, l = q
query_ls[u].append(l)
while u > 0:
if required[u] >= l:
break
required[u] = l
u >>= 1
cache_dp = [None] * (n + 1)
cache_dp[0] = {0: 0}
cache_max = [(-1, -1)] * (n + 1)
ans = [0] * inp[n * 2]
for u in range(1, n + 1):
r = required[u]
if r == -1:
continue
par = cache_dp[u >> 1]
cur_w, cur_v = cache_max[u >> 1]
if cur_w > r:
cur_w, cur_v = max(
(itm for itm in par.items() if itm[0] <= r), default=(-1, -1)
)
dp = par.copy()
v = vvv[u]
w = www[u]
for cw, cv in par.items():
nw = cw + w
if nw > r:
continue
nv = cv + v
if nw not in dp or dp[nw] < nv:
dp[nw] = nv
if nv > cur_v:
cur_w = nw
cur_v = nv
elif nv == cur_v and cur_w > nw:
cur_w = nw
if u in query_ls:
for l in query_ls[u]:
if cur_w <= l:
tmp = cur_v
else:
tmp = max((v for w, v in dp.items() if w <= l), default=0)
ans[query_idx[u, l]] = tmp
cache_dp[u] = dp
print("\n".join(map(str, ans)))
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s264913968 | Runtime Error | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys
input = sys.stdin.readline
n = int(input())
lm = 10**5 + 1
h = min(n, 1 << 10) + 1
l = [list(map(int, input().split())) for i in range(n)]
dp = [None] * h
dp[0] = [0] * lm
for i in range(1, h):
v, w = l[i - 1]
p = i // 2
d = dp[p][:]
for j in range(lm - 1, w - 1, -1):
d[j] = max(d[j], d[j - w] + v)
dp[i] = d
q = int(input())
for _ in range(q):
v, m = map(int, input().split())
if v < h:
print(dp[v][m])
else:
vv = []
ww = []
while v >= h:
vv.append(l[v][0])
ww.append(l[v][1])
v >>= 1
ans = dp[v][m]
le = len(vv)
V = [0] * (1 << le)
W = [0] * (1 << le)
for i in range(1, 1 << le):
ind = i & (-i)
indd = ind.bit_length() - 1
wi = W[i - ind] + ww[indd]
W[i] = wi
if wi <= m:
vi = V[i - ind] + vv[indd]
V[i] = vi
ans = max(ans, vi + dp[v][m - wi])
print(ans)
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s557580545 | Accepted | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | import sys
input = sys.stdin.readline
N = int(input())
LIMIT = min(N, 4195)
V = [0] * N
W = [0] * N
for i in range(N):
nV, nW = map(int, input().split())
V[i] = nV
W[i] = nW
pre = [[] for i in range(LIMIT)]
for i in range(LIMIT):
if i == 0:
pre[i] = [(0, 0), (W[i], V[i])]
continue
curr = pre[i]
prev = pre[(i - 1) // 2]
nV, nW = V[i], W[i]
size = len(prev)
left = 0
right = 0
while left < size or right < size:
if (
left == size
or prev[left][0] > prev[right][0] + nW
or (
prev[left][0] == prev[right][0] + nW
and prev[left][1] < prev[right][1] + nV
)
):
if len(curr) == 0 or prev[right][1] + nV > curr[-1][1]:
curr.append((prev[right][0] + nW, prev[right][1] + nV))
right += 1
else:
if len(curr) == 0 or prev[left][1] > curr[-1][1]:
curr.append(prev[left])
left += 1
Q = int(input())
out = [0] * Q
for t in range(Q):
vert, L = map(int, input().split())
vert -= 1
stack = []
while vert >= LIMIT:
stack.append((V[vert], W[vert]))
vert = (vert - 1) // 2
prev = pre[vert]
best = 0
for i in range(1 << len(stack)):
sV = 0
sW = 0
red = i
for nV, nW in stack:
if red & 1:
sV += nV
sW += nW
red >>= 1
limit = L - sW
if limit < 0:
continue
lo = -1
hi = len(prev)
while hi - lo > 1:
test = (hi + lo) // 2
if prev[test][0] <= limit:
lo = test
else:
hi = test
if lo >= 0:
new = prev[lo][1] + sV
best = max(best, new)
out[t] = best
print("\n".join(map(str, out)))
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each integer i from 1 through Q, the i-th line should contain the response
to the i-th query.
* * * | s378388882 | Accepted | p02648 | Let v_i and L_i be the values v and L given in the i-th query. Then, Input is
given from Standard Input in the following format:
N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q | # D - Knapsack Queries on a tree
from sys import stdin
import bisect
readline = stdin.readline
bisect_right = bisect.bisect_right
n = int(readline())
v = [0] * n
w = [0] * n
for i in range(n):
v[i], w[i] = map(int, readline().split())
max_l = 10**5
vshift = 21
mask = (1 << vshift) - 1
# dp table (for some amount)
dp = [None] * min(n, 2**12)
# dp[vertex] = list of (weight, value)
dp[0] = [(0 << vshift) + 0, (w[0] << vshift) + v[0]]
for u in range(1, len(dp)):
parent = (u - 1) // 2
ls = dp[parent][:]
ls.extend(
x + (w[u] << vshift) + v[u] for x in dp[parent] if (x >> vshift) + w[u] <= max_l
)
ls.sort()
# remove unnecessary entries
tail = 0
for i in range(1, len(ls)):
if (ls[tail] >> vshift) == (ls[i] >> vshift):
ls[tail] = ls[i]
elif (ls[tail] & mask) < (ls[i] & mask):
tail += 1
ls[tail] = ls[i]
del ls[tail + 1 :]
dp[u] = ls
def solve(u, l):
if u < len(dp):
x = bisect_right(dp[u], (l << vshift) + mask) - 1
return dp[u][x] & mask
parent = (u - 1) // 2
s = solve(parent, l)
if l >= w[u]:
s = max(s, v[u] + solve(parent, l - w[u]))
return s
q = int(readline())
for i in range(q):
u, l = map(int, readline().split())
print(solve(u - 1, l))
| Statement
We have a rooted binary tree with N vertices, where the vertices are numbered
1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex
\left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a
weight of W_i. Now, process the following query Q times:
* Given are a vertex v of the tree and a positive integer L. Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L. Find the maximum possible total value of the chosen items.
Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect
parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k
(k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i. | [{"input": "3\n 1 2\n 2 3\n 3 4\n 3\n 1 1\n 2 5\n 3 5", "output": "0\n 3\n 3\n \n\nIn the first query, we are given only one choice: the item with (V, W)=(1,2).\nSince L = 1, we cannot actually choose it, so our response should be 0.\n\nIn the second query, we are given two choices: the items with (V, W)=(1,2) and\n(V, W)=(2,3). Since L = 5, we can choose both of them, so our response should\nbe 3.\n\n* * *"}, {"input": "15\n 123 119\n 129 120\n 132 112\n 126 109\n 118 103\n 115 109\n 102 100\n 130 120\n 105 105\n 132 115\n 104 102\n 107 107\n 127 116\n 121 104\n 121 115\n 8\n 8 234\n 9 244\n 10 226\n 11 227\n 12 240\n 13 237\n 14 206\n 15 227", "output": "256\n 255\n 250\n 247\n 255\n 259\n 223\n 253"}] |
For each dataset, print in a line the areas looking from above of all the
pieces that exist upon completion of the _n_ cuts specified in the dataset.
They should be in ascending order and separated by a space. When multiple
pieces have the same area, print it as many times as the number of the pieces. | s600887867 | Accepted | p00730 | The input is a sequence of datasets, each of which is of the following format.
> _n_ _w_ _d_
> _p_ 1 _s_ 1
> ...
> _p n_ _s n_
>
The first line starts with an integer _n_ that is between 0 and 100 inclusive.
It is the number of cuts to be performed. The following _w_ and _d_ in the
same line are integers between 1 and 100 inclusive. They denote the width and
depth of the cake, respectively. Assume in the sequel that the cake is placed
so that _w_ and _d_ are the lengths in the east-west and north-south
directions, respectively.
Each of the following _n_ lines specifies a single cut, cutting one and only
one piece into two. _p i_ is an integer between 1 and _i_ inclusive and is the
identification number of the piece that is the target of the _i_ -th cut. Note
that, just before the _i_ -th cut, there exist exactly _i_ pieces. Each piece
in this stage has a unique identification number that is one of 1, 2, ..., _i_
and is defined as follows:
* The earlier a piece was born, the smaller its identification number is.
* Of the two pieces born at a time by the same cut, the piece with the smaller area (looking from above) has the smaller identification number. If their areas are the same, you may define as you like the order between them, since your choice in this case has no influence on the final answer.
Note that identification numbers are adjusted after each cut.
_s i_ is an integer between 1 and 1000 inclusive and specifies the starting
point of the _i_ -th cut. From the northwest corner of the piece whose
identification number is _p i_, you can reach the starting point by traveling
_s i_ in the clockwise direction around the piece. You may assume that the
starting point determined in this way cannot be any one of the four corners of
the piece. The _i_ -th cut surface is orthogonal to the side face on which the
starting point exists.
The end of the input is indicated by a line with three zeros. | import sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = 10**10
def I():
return int(input())
def F():
return float(input())
def S():
return input()
def LI():
return [int(x) for x in input().split()]
def LI_():
return [int(x) - 1 for x in input().split()]
def LF():
return [float(x) for x in input().split()]
def LS():
return input().split()
def resolve():
while True:
n, w, d = LI()
if n == 0 and w == 0 and d == 0:
break
cake = []
cake.append([w, d])
for _ in range(n):
ps = LI()
p = ps[0] - 1
s = ps[1]
# ケーキカット
cake_w = cake[p][0]
cake_d = cake[p][1]
s %= (cake_w + cake_d) * 2
if s < cake_w:
new_cake_s = [min(s, cake_w - s), cake_d]
new_cake_l = [max(s, cake_w - s), cake_d]
elif cake_w < s < cake_w + cake_d:
new_cake_s = [cake_w, min(s - cake_w, cake_w + cake_d - s)]
new_cake_l = [cake_w, max(s - cake_w, cake_w + cake_d - s)]
elif cake_w + cake_d < s < cake_w + cake_d + cake_w:
new_cake_s = [
min(s - (cake_w + cake_d), cake_w + cake_d + cake_w - s),
cake_d,
]
new_cake_l = [
max(s - (cake_w + cake_d), cake_w + cake_d + cake_w - s),
cake_d,
]
else:
new_cake_s = [
cake_w,
min(
s - (cake_w + cake_d + cake_w),
cake_w + cake_d + cake_w + cake_d - s,
),
]
new_cake_l = [
cake_w,
max(
s - (cake_w + cake_d + cake_w),
cake_w + cake_d + cake_w + cake_d - s,
),
]
# id付け替え
del cake[p]
# 新ケーキ追加
cake.append(new_cake_s)
cake.append(new_cake_l)
print(*sorted([i[0] * i[1] for i in cake]))
if __name__ == "__main__":
resolve()
| C: Cut the Cake
Today is the birthday of Mr. Bon Vivant, who is known as one of the greatest
_p atissiers_ in the world. Those who are invited to his birthday party are
_gourmets_ from around the world. They are eager to see and eat his extremely
creative cakes. Now a large box-shaped cake is being carried into the party.
It is not beautifully decorated and looks rather simple, but it must be
delicious beyond anyone's imagination. Let us cut it into pieces with a knife
and serve them to the guests attending the party.
The cake looks rectangular, viewing from above (Figure C-1). As exemplified in
Figure C-2, the cake will iteratively be cut into pieces, where on each cut
exactly a single piece is cut into two smaller pieces. Each cut surface must
be orthogonal to the bottom face and must be orthogonal or parallel to a side
face. So, every piece shall be rectangular looking from above and every side
face vertical.

Figure C-1: The top view of the cake

Figure C-2: Cutting the cake into pieces
Piece sizes in Figure C-2 vary significantly and it may look unfair, but you
don't have to worry. Those guests who would like to eat as many sorts of cakes
as possible often prefer smaller pieces. Of course, some prefer larger ones.
Your mission of this problem is to write a computer program that simulates the
cutting process of the cake and reports the size of each piece. | [{"input": "5 6\n 1 18\n 2 19\n 1 2\n 3 4 1\n 1 1\n 2 1\n 3 1\n 0 2 5\n 0 0 0", "output": "4 6 16\n 1 1 1 1\n 10"}] |
For each dataset, print in a line the areas looking from above of all the
pieces that exist upon completion of the _n_ cuts specified in the dataset.
They should be in ascending order and separated by a space. When multiple
pieces have the same area, print it as many times as the number of the pieces. | s697299658 | Wrong Answer | p00730 | The input is a sequence of datasets, each of which is of the following format.
> _n_ _w_ _d_
> _p_ 1 _s_ 1
> ...
> _p n_ _s n_
>
The first line starts with an integer _n_ that is between 0 and 100 inclusive.
It is the number of cuts to be performed. The following _w_ and _d_ in the
same line are integers between 1 and 100 inclusive. They denote the width and
depth of the cake, respectively. Assume in the sequel that the cake is placed
so that _w_ and _d_ are the lengths in the east-west and north-south
directions, respectively.
Each of the following _n_ lines specifies a single cut, cutting one and only
one piece into two. _p i_ is an integer between 1 and _i_ inclusive and is the
identification number of the piece that is the target of the _i_ -th cut. Note
that, just before the _i_ -th cut, there exist exactly _i_ pieces. Each piece
in this stage has a unique identification number that is one of 1, 2, ..., _i_
and is defined as follows:
* The earlier a piece was born, the smaller its identification number is.
* Of the two pieces born at a time by the same cut, the piece with the smaller area (looking from above) has the smaller identification number. If their areas are the same, you may define as you like the order between them, since your choice in this case has no influence on the final answer.
Note that identification numbers are adjusted after each cut.
_s i_ is an integer between 1 and 1000 inclusive and specifies the starting
point of the _i_ -th cut. From the northwest corner of the piece whose
identification number is _p i_, you can reach the starting point by traveling
_s i_ in the clockwise direction around the piece. You may assume that the
starting point determined in this way cannot be any one of the four corners of
the piece. The _i_ -th cut surface is orthogonal to the side face on which the
starting point exists.
The end of the input is indicated by a line with three zeros. | # -*- coding: utf-8 -*-
from sys import setrecursionlimit
setrecursionlimit(100000)
class Cake:
def __init__(self, N, W, D):
self.P = [-1] * 2 * (N + 1)
self.L = [-1] * 2 * (N + 1)
self.R = [-1] * 2 * (N + 1)
self.W = [0] * 2 * (N + 1)
self.W[1] = W
self.D = [0] * 2 * (N + 1)
self.D[1] = D
self.C = [-1] * 2 * (N + 1)
self.C[1] = 1
def search(self, target, now):
if self.C[now] == 1:
return now
if self.C[self.L[now]] >= target:
now = self.search(target, self.L[now])
else:
now = self.search(target - self.C[self.L[now]], self.R[now])
return now
def cut(self, target, s, l):
w = self.W[target]
d = self.D[target]
L = w + d
s %= L
if s <= w:
nw, nW = s, w - s
if nw > nW:
nw, nW = nW, nw
nd, nD = d, d
else:
s -= w
nd, nD = s, d - s
if nd > nD:
nd, nD = nD, nd
nw, nW = w, w
r = l + 1
self.L[target], self.R[target] = l, r
self.P[l], self.P[r] = target, target
self.W[l], self.W[r] = nw, nW
self.D[l], self.D[r] = nd, nD
self.C[l], self.C[r] = 1, 1
par = target
while par != -1:
self.C[par] += 1
par = self.P[par]
def show(self):
tmp = []
for i in range(len(self.C)):
if self.C[i] == 1:
tmp.append(self.W[i] * self.D[i])
print(" ".join(map(str, sorted(tmp))))
N, W, D = map(int, input().split())
while W:
cake = Cake(N, W, D)
for i in range(N):
p, s = map(int, input().split())
target = cake.search(p, 1)
cake.cut(target, s, 2 * (i + 1))
cake.show()
N, W, D = map(int, input().split())
| C: Cut the Cake
Today is the birthday of Mr. Bon Vivant, who is known as one of the greatest
_p atissiers_ in the world. Those who are invited to his birthday party are
_gourmets_ from around the world. They are eager to see and eat his extremely
creative cakes. Now a large box-shaped cake is being carried into the party.
It is not beautifully decorated and looks rather simple, but it must be
delicious beyond anyone's imagination. Let us cut it into pieces with a knife
and serve them to the guests attending the party.
The cake looks rectangular, viewing from above (Figure C-1). As exemplified in
Figure C-2, the cake will iteratively be cut into pieces, where on each cut
exactly a single piece is cut into two smaller pieces. Each cut surface must
be orthogonal to the bottom face and must be orthogonal or parallel to a side
face. So, every piece shall be rectangular looking from above and every side
face vertical.

Figure C-1: The top view of the cake

Figure C-2: Cutting the cake into pieces
Piece sizes in Figure C-2 vary significantly and it may look unfair, but you
don't have to worry. Those guests who would like to eat as many sorts of cakes
as possible often prefer smaller pieces. Of course, some prefer larger ones.
Your mission of this problem is to write a computer program that simulates the
cutting process of the cake and reports the size of each piece. | [{"input": "5 6\n 1 18\n 2 19\n 1 2\n 3 4 1\n 1 1\n 2 1\n 3 1\n 0 2 5\n 0 0 0", "output": "4 6 16\n 1 1 1 1\n 10"}] |
Print the minimum number of operations required to achieve the objective.
* * * | s100429409 | Accepted | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | n, x = map(int, input().split())
ar = list(map(int, input().split()))
pr, ans = 0, 0
for e in ar:
if pr + e > x:
l = pr + e - x
ans += l
e -= l
pr = e
print(ans)
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s548351944 | Wrong Answer | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | s = input()
print(["Second", "First"][(len(s) + (s[0] == s[-1])) % 2])
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s871259804 | Runtime Error | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | n,x=map(int,input().split())
a=list(map(int,input().split()))
ret=0
if a[0]>x:
ret+=a[0]-x
a[0]-=x
for i in range(1:n):
if a[i]+a[i-1]>x:
ret+=a[i]+a[i-1]-x
a[i]=a[i]+a[i-1]-x
print(ret) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s105464647 | Runtime Error | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | from heapq import heapify, heappop, heappush
xs, ys, xt, yt = map(int, input().split())
P = []
inf = float("inf")
P.append((xs, ys, 0))
N = int(input())
for i in range(N):
x, y, r = map(int, input().split())
P.append((x, y, r))
P.append((xt, yt, 0))
G = [set() for i in range(N + 2)]
for i in range(N + 2):
for j in range(N + 2):
if i != j:
x1, y1, r1, x2, y2, r2 = (
P[i][0],
P[i][1],
P[i][2],
P[j][0],
P[j][1],
P[j][2],
)
d = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2)
if d <= r1 + r2:
G[i].add((0, j))
else:
G[i].add((d - r1 - r2, j))
def dijkstra(s, n, links):
cost = [inf] * n
cost[s] = 0
heap = [(0, s)]
heapify(heap)
while heap:
hc, hp = heappop(heap)
for c, p in links[hp]:
if c + hc < cost[p]:
cost[p] = c + hc
heappush(heap, (cost[p], p))
return cost
c = dijkstra(0, N + 2, G)
print(c[-1])
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s759022616 | Runtime Error | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | from collections import defaultdict
import heapq
from math import sqrt
# -*- coding: utf-8 -*-
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
def calc(b1, b2):
x1, y1, r1 = b1
x2, y2, r2 = b2
d = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
return max(d - (r1 + r2), 0)
sx, sy, gx, gy = map(int, input().split())
N = int(input())
barriers = (
[[sx, sy, 0]] + [list(map(int, input().split())) for _ in range(N)] + [[gx, gy, 0]]
)
mat = [[0] * (N + 2) for _ in range(N + 2)]
for row in range(N + 2):
for col in range(row + 1, N + 2):
d = calc(barriers[row], barriers[col])
mat[row][col] = d
mat[col][row] = d
# 視点からの距離
dist = [float("inf")] * (N + 2)
dist[0] = 0
# 最短経路での一つ前のノード
prev = defaultdict(lambda: None)
Q = []
# Q->[dist from start,node])
heapq.heappush(Q, (0, 0))
while Q:
dist_to_node, node = heapq.heappop(Q)
if dist[node] < dist_to_node:
continue
else:
for v in range(N + 2):
weight = mat[node][v]
alt = dist_to_node + weight
if dist[v] > alt:
dist[v] = alt
prev[v] = node
heapq.heappush(Q, (alt, v))
print(dist[-1])
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s201571153 | Runtime Error | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | N,x=map(int,input().split(' '))
A=list(map(int,input().split(' ')))
B=[a for a in A]
if N==2:
print(A[0]+A[1]-x)
else:
for i in range(N-3):
B[i+1] -= min(B[i+1], max(0,(B[i]+B[i+1]-x)))
B[i] -= max(B[i]-x, 0)
B[-2] -= min(B[-2], max(0, (B[-3]+B[-2]-x), (B[-1]+B[-2]-x)))
B[-3] -= max(0, (B[-3]-x))
B[-1] -= max(0, (B[-1]-x))
print(sum[A[i]-B[i] for i in range(N)]) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s726935571 | Runtime Error | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | /*
██╗ ██████╗ ██╗███╗ ██╗ ██╗ ██╗███████╗
██║██╔═══██╗██║████╗ ██║ ██║ ██║██╔════╝
██║██║ ██║██║██╔██╗ ██║ ██║ ██║███████╗
██ ██║██║ ██║██║██║╚██╗██║ ██║ ██║╚════██║
╚█████╔╝╚██████╔╝██║██║ ╚████║ ╚██████╔╝███████║
╚════╝ ╚═════╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝
*/
//password:+BdCHpO8dQvpo5fnV3/u
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e5 + 5;
const int inf = 0x3f3f3f3f;
int main() {
ll n,x;
cin>>n>>x;
vector<ll>a(n+1);
for(int i=1;i<=n;i++)
cin>>a[i];
int ans=0;
for(int i=1;i<n;i++)
{
if(a[i]+a[i+1]>x)
{
int res=a[i]+a[i+1]-x;
ans+=res;
if(2<=i+1<=n-1)
{
if(a[i+1]>=res) a[i+1]-=res;
else
{
a[i+1]=0;
a[i]-=res-a[i+1];
}
}
}
}
cout<<ans;
return 0;
} | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s693358039 | Runtime Error | p03864 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | from heapq import heappop, heappush
INF = 10**20
xs, ys, xt, yt = map(int, input().split())
N = int(input())
circle = [list(map(int, input().split())) for _ in range(N)]
circle = [[xs, ys, 0]] + circle + [[xt, yt, 0]]
edges_lst = [[] for _ in range(N + 2)]
for i, (x1, y1, r1) in enumerate(circle):
for j, (x2, y2, r2) in enumerate(circle[i + 1 :]):
j += i + 1
d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
dist = max(0, d - r1 - r2)
edges_lst[i].append((j, dist))
edges_lst[j].append((i, dist))
def dijkstra():
que = []
heappush(que, (0, 0))
dist_lst = [INF] * (N + 2)
dist_lst[0] = 0
while que:
dist, node = heappop(que)
for to, cost in edges_lst[node]:
if dist_lst[to] > cost + dist:
dist_lst[to] = cost + dist
heappush(que, (cost + dist, to))
return dist_lst[-1]
print("{:.10f}".format(dijkstra()))
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
If it is impossible to deactivate all the bombs at the same time, print `-1`.
If it is possible to do so, print a set of cords that should be cut, as
follows:
k
c_1 c_2 \dots c_k
Here, k is the number of cords (possibly 0), and c_1, c_2, \dots, c_k
represent the cords that should be cut. 1 \leq c_1 < c_2 < \dots < c_k \leq M
must hold.
* * * | s788564379 | Wrong Answer | p02776 | Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_N B_N
L_1 R_1
:
L_M R_M | import bisect
import os
import sys
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10**9)
INF = float("inf")
IINF = 10**18
MOD = 10**9 + 7
# MOD = 998244353
N, M = list(map(int, sys.stdin.buffer.readline().split()))
AB = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
LR = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(M)]
AB.sort()
odd = 0
# 偶奇が変わる値
changes = [0]
for a, b in AB:
if odd == b:
continue
odd = b
changes.append(a)
if len(changes) & 1:
changes.pop()
if len(changes) == 0:
print(0)
exit()
size = len(changes)
graph = [[] for _ in range(size)]
for i, (l, r) in enumerate(LR, start=1):
# l 未満が全部変わる
v = bisect.bisect_left(changes, l) - 1
# r 以下が全部変わる
u = bisect.bisect_right(changes, r) - 1
graph[v].append((u, i))
graph[u].append((v, i))
parity = [1] * size
# 適当に全域木を作って 1 を押し出していけばいい
seen = [False] * size
trees = []
for root in range(size):
if seen[root] or not graph[root]:
continue
edges = []
seen[root] = True
stack = [root]
while stack:
v = stack.pop()
for u, i in graph[v]:
if seen[u]:
continue
seen[u] = True
stack.append(u)
edges.append((v, u, i))
# 頂点が1つしかない
if not edges and parity[root] == 1:
print(-1)
exit()
trees.append(edges)
graph = [[] for _ in range(size)]
degrees = [0] * size
for edges in trees:
for v, u, i in edges:
graph[v].append((u, i))
graph[u].append((v, i))
degrees[v] += 1
degrees[u] += 1
ans = []
seen = [False] * size
stack = []
for v, d in enumerate(degrees):
if d == 1:
stack.append(v)
while stack:
v = stack.pop()
if degrees[v] == 0:
continue
assert degrees[v] == 1
if seen[v]:
continue
seen[v] = True
degrees[v] = 0
# 葉っぱから内側にずらしてく
for u, i in graph[v]:
if seen[u]:
continue
if parity[v] == parity[u] == 1:
parity[u] = parity[v] = 0
ans.append(i)
elif parity[v] == 1 and parity[u] == 0:
parity[u] = 1
parity[v] = 0
ans.append(i)
degrees[u] -= 1
if degrees[u] == 1:
stack.append(u)
if 1 in parity:
print(-1)
else:
print(len(ans))
print(*sorted(ans))
| Statement
After being invaded by the Kingdom of AlDebaran, bombs are planted throughout
our country, AtCoder Kingdom.
Fortunately, our military team called ABC has managed to obtain a device that
is a part of the system controlling the bombs.
There are N bombs, numbered 1 to N, planted in our country. Bomb i is planted
at the coordinate A_i. It is currently activated if B_i=1, and deactivated if
B_i=0.
The device has M cords numbered 1 to M. If we cut Cord j, the states of all
the bombs planted between the coordinates L_j and R_j (inclusive) will be
switched - from activated to deactivated, and vice versa.
Determine whether it is possible to deactivate all the bombs at the same time.
If the answer is yes, output a set of cords that should be cut. | [{"input": "3 4\n 5 1\n 10 1\n 8 0\n 1 10\n 4 5\n 6 7\n 8 9", "output": "2\n 1 4\n \n\nThere are two activated bombs at the coordinates 5, 10, and one deactivated\nbomb at the coordinate 8.\n\nCutting Cord 1 switches the states of all the bombs planted between the\ncoordinates 1 and 10, that is, all of the three bombs.\n\nCutting Cord 4 switches the states of all the bombs planted between the\ncoordinates 8 and 9, that is, Bomb 3.\n\nThus, we can deactivate all the bombs by cutting Cord 1 and Cord 4.\n\n* * *"}, {"input": "4 2\n 2 0\n 3 1\n 5 1\n 7 0\n 1 4\n 4 7", "output": "-1\n \n\nCutting any set of cords will not deactivate all the bombs at the same time.\n\n* * *"}, {"input": "3 2\n 5 0\n 10 0\n 8 0\n 6 9\n 66 99", "output": "0\n \n \n\nAll the bombs are already deactivated, so we do not need to cut any cord.\n\n* * *"}, {"input": "12 20\n 536130100 1\n 150049660 1\n 79245447 1\n 132551741 0\n 89484841 1\n 328129089 0\n 623467741 0\n 248785745 0\n 421631475 0\n 498966877 0\n 43768791 1\n 112237273 0\n 21499042 142460201\n 58176487 384985131\n 88563042 144788076\n 120198276 497115965\n 134867387 563350571\n 211946499 458996604\n 233934566 297258009\n 335674184 555985828\n 414601661 520203502\n 101135608 501051309\n 90972258 300372385\n 255474956 630621190\n 436210625 517850028\n 145652401 192476406\n 377607297 520655694\n 244404406 304034433\n 112237273 359737255\n 392593015 463983307\n 150586788 504362212\n 54772353 83124235", "output": "5\n 1 7 8 9 11\n \n\nIf there are multiple sets of cords that deactivate all the bombs when cut,\nany of them can be printed."}] |
If it is impossible to deactivate all the bombs at the same time, print `-1`.
If it is possible to do so, print a set of cords that should be cut, as
follows:
k
c_1 c_2 \dots c_k
Here, k is the number of cords (possibly 0), and c_1, c_2, \dots, c_k
represent the cords that should be cut. 1 \leq c_1 < c_2 < \dots < c_k \leq M
must hold.
* * * | s061345230 | Runtime Error | p02776 | Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_N B_N
L_1 R_1
:
L_M R_M | # -*- coding: utf-8 -*-
def solve():
N, M = map(int, input().split())
L = sorted([tuple(map(int, input().split())) for _ in range(N)])
A = [l[0] for l in L]
b = int("".join([str(l[1]) for l in L]), 2)
K = [tuple(map(int, input().split())) for _ in range(M)]
LR = sorted(
[int("".join(["1" if l <= a <= r else "0" for a in A]), 2) for l, r in K],
reverse=1,
)
print(f"{b:0>{N:d}b}")
for lr in LR:
print(f"{lr:0>{N:d}b}")
res = 0
return str(res)
if __name__ == "__main__":
print(solve())
| Statement
After being invaded by the Kingdom of AlDebaran, bombs are planted throughout
our country, AtCoder Kingdom.
Fortunately, our military team called ABC has managed to obtain a device that
is a part of the system controlling the bombs.
There are N bombs, numbered 1 to N, planted in our country. Bomb i is planted
at the coordinate A_i. It is currently activated if B_i=1, and deactivated if
B_i=0.
The device has M cords numbered 1 to M. If we cut Cord j, the states of all
the bombs planted between the coordinates L_j and R_j (inclusive) will be
switched - from activated to deactivated, and vice versa.
Determine whether it is possible to deactivate all the bombs at the same time.
If the answer is yes, output a set of cords that should be cut. | [{"input": "3 4\n 5 1\n 10 1\n 8 0\n 1 10\n 4 5\n 6 7\n 8 9", "output": "2\n 1 4\n \n\nThere are two activated bombs at the coordinates 5, 10, and one deactivated\nbomb at the coordinate 8.\n\nCutting Cord 1 switches the states of all the bombs planted between the\ncoordinates 1 and 10, that is, all of the three bombs.\n\nCutting Cord 4 switches the states of all the bombs planted between the\ncoordinates 8 and 9, that is, Bomb 3.\n\nThus, we can deactivate all the bombs by cutting Cord 1 and Cord 4.\n\n* * *"}, {"input": "4 2\n 2 0\n 3 1\n 5 1\n 7 0\n 1 4\n 4 7", "output": "-1\n \n\nCutting any set of cords will not deactivate all the bombs at the same time.\n\n* * *"}, {"input": "3 2\n 5 0\n 10 0\n 8 0\n 6 9\n 66 99", "output": "0\n \n \n\nAll the bombs are already deactivated, so we do not need to cut any cord.\n\n* * *"}, {"input": "12 20\n 536130100 1\n 150049660 1\n 79245447 1\n 132551741 0\n 89484841 1\n 328129089 0\n 623467741 0\n 248785745 0\n 421631475 0\n 498966877 0\n 43768791 1\n 112237273 0\n 21499042 142460201\n 58176487 384985131\n 88563042 144788076\n 120198276 497115965\n 134867387 563350571\n 211946499 458996604\n 233934566 297258009\n 335674184 555985828\n 414601661 520203502\n 101135608 501051309\n 90972258 300372385\n 255474956 630621190\n 436210625 517850028\n 145652401 192476406\n 377607297 520655694\n 244404406 304034433\n 112237273 359737255\n 392593015 463983307\n 150586788 504362212\n 54772353 83124235", "output": "5\n 1 7 8 9 11\n \n\nIf there are multiple sets of cords that deactivate all the bombs when cut,\nany of them can be printed."}] |
If it is impossible to deactivate all the bombs at the same time, print `-1`.
If it is possible to do so, print a set of cords that should be cut, as
follows:
k
c_1 c_2 \dots c_k
Here, k is the number of cords (possibly 0), and c_1, c_2, \dots, c_k
represent the cords that should be cut. 1 \leq c_1 < c_2 < \dots < c_k \leq M
must hold.
* * * | s175273782 | Wrong Answer | p02776 | Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_N B_N
L_1 R_1
:
L_M R_M | print("6")
print("2 5 11 15 16 18")
| Statement
After being invaded by the Kingdom of AlDebaran, bombs are planted throughout
our country, AtCoder Kingdom.
Fortunately, our military team called ABC has managed to obtain a device that
is a part of the system controlling the bombs.
There are N bombs, numbered 1 to N, planted in our country. Bomb i is planted
at the coordinate A_i. It is currently activated if B_i=1, and deactivated if
B_i=0.
The device has M cords numbered 1 to M. If we cut Cord j, the states of all
the bombs planted between the coordinates L_j and R_j (inclusive) will be
switched - from activated to deactivated, and vice versa.
Determine whether it is possible to deactivate all the bombs at the same time.
If the answer is yes, output a set of cords that should be cut. | [{"input": "3 4\n 5 1\n 10 1\n 8 0\n 1 10\n 4 5\n 6 7\n 8 9", "output": "2\n 1 4\n \n\nThere are two activated bombs at the coordinates 5, 10, and one deactivated\nbomb at the coordinate 8.\n\nCutting Cord 1 switches the states of all the bombs planted between the\ncoordinates 1 and 10, that is, all of the three bombs.\n\nCutting Cord 4 switches the states of all the bombs planted between the\ncoordinates 8 and 9, that is, Bomb 3.\n\nThus, we can deactivate all the bombs by cutting Cord 1 and Cord 4.\n\n* * *"}, {"input": "4 2\n 2 0\n 3 1\n 5 1\n 7 0\n 1 4\n 4 7", "output": "-1\n \n\nCutting any set of cords will not deactivate all the bombs at the same time.\n\n* * *"}, {"input": "3 2\n 5 0\n 10 0\n 8 0\n 6 9\n 66 99", "output": "0\n \n \n\nAll the bombs are already deactivated, so we do not need to cut any cord.\n\n* * *"}, {"input": "12 20\n 536130100 1\n 150049660 1\n 79245447 1\n 132551741 0\n 89484841 1\n 328129089 0\n 623467741 0\n 248785745 0\n 421631475 0\n 498966877 0\n 43768791 1\n 112237273 0\n 21499042 142460201\n 58176487 384985131\n 88563042 144788076\n 120198276 497115965\n 134867387 563350571\n 211946499 458996604\n 233934566 297258009\n 335674184 555985828\n 414601661 520203502\n 101135608 501051309\n 90972258 300372385\n 255474956 630621190\n 436210625 517850028\n 145652401 192476406\n 377607297 520655694\n 244404406 304034433\n 112237273 359737255\n 392593015 463983307\n 150586788 504362212\n 54772353 83124235", "output": "5\n 1 7 8 9 11\n \n\nIf there are multiple sets of cords that deactivate all the bombs when cut,\nany of them can be printed."}] |
Print the area (the number of 0s) of the largest square. | s007777029 | Accepted | p02326 | H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are
given. In the following H lines, ci,j, elements of the H × W matrix, are
given. | t, *L = open(0)
H, W = map(int, t.split())
bef = [0] * (W + 1)
a = 0
for l in L:
cur = [0] * (W + 1)
for i in range(W):
if l[i * 2] == "0":
cur[i + 1] = min(cur[i], bef[i], bef[i + 1]) + 1
a = max(a, max(cur))
bef = cur
print(a**2)
| Largest Square
Given a matrix (H × W) which contains only 1 and 0, find the area of the
largest square matrix which only contains 0s. | [{"input": "5\n 0 0 1 0 0\n 1 0 0 0 0\n 0 0 0 1 0\n 0 0 0 1 0", "output": "4"}] |
Print the area (the number of 0s) of the largest square. | s954079951 | Accepted | p02326 | H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are
given. In the following H lines, ci,j, elements of the H × W matrix, are
given. | import sys
def solve():
file_input = sys.stdin
H, W = map(int, file_input.readline().split())
side_length = 0
prev = [0] * (W + 1)
for line in file_input:
tile_line = map(int, line.split())
current = [0] * (W + 1)
for i, tpl in enumerate(zip(tile_line, prev, prev[1:]), start=1):
t, p1, p2 = tpl
if t:
current[i] = 0
else:
current[i] = min(p1, p2, current[i - 1]) + 1
prev = current
side_length = max(side_length, max(current))
print(side_length**2)
solve()
| Largest Square
Given a matrix (H × W) which contains only 1 and 0, find the area of the
largest square matrix which only contains 0s. | [{"input": "5\n 0 0 1 0 0\n 1 0 0 0 0\n 0 0 0 1 0\n 0 0 0 1 0", "output": "4"}] |
Print the area (the number of 0s) of the largest square. | s881991558 | Accepted | p02326 | H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are
given. In the following H lines, ci,j, elements of the H × W matrix, are
given. | h, w = map(int, input().split())
mp = []
for _ in range(h):
lst = list(map(int, input().split()))
cum = []
acc = 0
for i in lst:
if i == 0:
acc += 1
else:
acc = 0
cum.append(acc)
mp.append(cum)
mp.append([-1] * w)
ans = 0
for x in range(w):
score_stack = []
ind_stack = []
for y in range(h + 1):
# print(score_stack, ind_stack)
score = mp[y][x]
if score_stack == []:
score_stack.append(score)
ind_stack.append(y)
else:
last_score = score_stack[-1]
if last_score < score:
score_stack.append(score)
ind_stack.append(y)
elif last_score == score:
continue
else:
while score_stack != [] and score_stack[-1] >= score:
last_score = score_stack.pop()
last_ind = ind_stack.pop()
# print(last_score, last_ind, ans)
ans = max(ans, min(y - last_ind, last_score) ** 2)
score_stack.append(score)
ind_stack.append(last_ind)
print(ans)
| Largest Square
Given a matrix (H × W) which contains only 1 and 0, find the area of the
largest square matrix which only contains 0s. | [{"input": "5\n 0 0 1 0 0\n 1 0 0 0 0\n 0 0 0 1 0\n 0 0 0 1 0", "output": "4"}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s335369629 | Accepted | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | # At DP F
def paths(M):
A = [[0] * len(M[0]) for _ in range(len(M))]
A[0][0] = 1
for row in range(len(A)):
for col in range(len(A[row])):
count = A[row][col]
if row > 0 and M[row - 1][col] != "#":
count += A[row - 1][col]
if col > 0 and M[row][col - 1] != "#":
count += A[row][col - 1]
A[row][col] = count
return A[-1][-1] % 1000000007
X1 = ["...#", ".#..", "...."]
assert paths(X1) == 3
X2 = [
"..",
"#.",
"..",
".#",
"..",
]
assert paths(X2) == 0
X3 = ["..#..", ".....", "#...#", ".....", "..#.."]
assert paths(X3) == 24
X4 = [
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
"....................",
]
assert paths(X4) == 345263555
h, w = map(int, input().split())
M = [None] * h
for i in range(h):
row = input().strip()
M[i] = row
ans = paths(M)
print(ans)
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s504175245 | Accepted | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2019/3/7
Update on 2019/3/
Solved on 2019/3/
@author: shinjisu
"""
# Educational Dynamic Programming
# import math
# import numpy as np
# import sys
# sys.setrecursionlimit(10**6)
def getInt():
return int(input())
def getIntList():
return [int(x) for x in input().split()]
# def getIntList(): return np.array(input().split(), dtype=np.longlong)
def zeros(n):
return [0] * n
# def zeros(n): return np.zeros(n, dtype=np.longlong)
def getIntLines(n):
return [int(input()) for i in range(n)]
def getIntLines(n):
data = zeros(n)
for i in range(n):
data[i] = getInt()
return data
def getIntMat(n, m): # n行に渡って、1行にm個の整数
mat = zeros((n, m))
# dmp(mat)
for i in range(n):
mat[i] = getIntList()
return mat
def zeros2(n, m):
return [zeros(m) for i in range(n)] # obsoleted zeros((n, m))で代替
ALPHABET = [chr(i + ord("a")) for i in range(26)]
DIGIT = [chr(i + ord("0")) for i in range(10)]
N1097 = 10**9 + 7
INF = 10**18
def dmp(x, cmt=""):
global debug
if debug:
if cmt != "":
print(cmt, ": ", end="")
print(x)
return x
def prob_H_v1(): # Grid 1 AC 10 TLE 6
H, W = getIntList()
dmp((H, W), "H, W")
a = []
for i in range(H):
a.append(input())
dmp(a)
WALL = "#"
BLANK = "."
dp = zeros((H + 1, W + 1))
dp[1, 1] = 1
dmp(dp, "dp initial")
for i in range(H):
for j in range(W):
if a[i][j] == BLANK and (i > 0 or j > 0):
dp[i + 1, j + 1] = (dp[i, j + 1] + dp[i + 1, j]) % N1097
dmp(dp, "dp")
return dp[H, W]
def prob_H_v2(): # Grid 1 AC 11 TLE 5
H, W = getIntList()
dmp((H, W), "H, W")
a = []
for i in range(H):
a.append(input())
dmp(a)
WALL = "#"
BLANK = "."
dp = zeros((H + 1, W + 1))
dp[1, 1] = 1
dmp(dp, "dp initial")
for i in range(1, H):
if a[i][0] == BLANK:
dp[i + 1, 1] = dp[i, 1]
for j in range(1, W):
if a[0][j] == BLANK:
dp[1, j + 1] = dp[1, j]
for i in range(1, H):
for j in range(1, W):
if a[i][j] == BLANK:
dp[i + 1, j + 1] = (dp[i, j + 1] + dp[i + 1, j]) % N1097
dmp(dp, "dp")
return dp[H, W]
def prob_H(): # Grid 1 AC 11 TLE 5
H, W = getIntList()
dmp((H, W), "H, W")
a = []
for i in range(H):
a.append(input())
dmp(a)
WALL = "#"
BLANK = "."
dp = zeros2(H + 1, W + 1)
dp[0][1] = 1 # [1,1]ではないことがポイント
dmp(dp, "dp initial")
for i in range(H):
for j in range(W):
if a[i][j] == WALL:
continue
dp[i + 1][j + 1] = (dp[i][j + 1] + dp[i + 1][j]) % N1097
dmp(dp, "dp")
return dp[H][W]
debug = False # True False
ans = prob_H()
print(ans)
# for row in ans:
# print(row)
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s148476481 | Accepted | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | #!/usr/bin/env python3
# vim: set fileencoding=utf-8
# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation
"""Module docstring
"""
import functools
import heapq
import itertools
import logging
import math
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
MODULO = pow(10, 9) + 7
def solve(values, h, w):
dp = [[0] * (1 + w) for _ in range(1 + h)]
dp[1][1] = 1
for i in range(h):
for j in range(w):
if i + j != 0 and values[i][j] == ".":
LOG.debug((i, j, values[i][j]))
dp[i + 1][j + 1] = (dp[i][j + 1] + dp[i + 1][j]) % MODULO
LOG.debug("\n".join(map(str, dp)))
return dp[h][w]
def do_job():
"Do the work"
LOG.debug("Start working")
# first line is number of test cases
H, W = map(int, input().split())
values = []
for _ in range(H):
values.append(input())
result = solve(values, H, W)
print(result)
def configure_log():
"Configure the log output"
log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(log_formatter)
LOG.addHandler(handler)
LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
LOG = logging.getLogger("template")
configure_log()
def main(argv=None):
"Program wrapper."
if argv is None:
argv = sys.argv[1:]
parser = ArgumentParser()
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_true",
default=False,
help="run as verbose mode",
)
args = parser.parse_args(argv)
if args.verbose:
LOG.setLevel(logging.DEBUG)
do_job()
return 0
if __name__ == "__main__":
import doctest
doctest.testmod()
sys.exit(main())
class memoized:
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s405356311 | Wrong Answer | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | N, M = map(int, input().split())
mod = 10**9 + 7
dp = [0] * ((N + 1) * (M + 1))
dp[1] = 1
for i in range(1, N + 1):
s = input().strip()
for j in range(1, M + 1):
if s[j - 1] == ".":
dp[i * (M + 1) + j] = dp[(i - 1) * (M + 1) + j] + dp[i * (M + 1) + j - 1]
print(dp[N * (M + 1) + M])
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s089387393 | Accepted | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | """ ===============================
-- @uthor : Kaleab Asfaw
-- Handle : kaleabasfaw2010
-- Bio : High-School Student
==============================="""
# Fast IO
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# Others
# from math import floor, ceil, gcd
# from decimal import Decimal as d
mod = 10**9 + 7
def lcm(x, y):
return (x * y) / (gcd(x, y))
def fact(x, mod=mod):
ans = 1
for i in range(1, x + 1):
ans = (ans * i) % mod
return ans
def arr2D(n, m, default=0):
lst = []
for i in range(n):
temp = [default] * m
lst.append(temp)
return lst
def sortDictV(x):
return {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
def solve(n, m, grid):
dp = arr2D(n, m)
dp[0][0] = 1
for i in range(n):
for j in range(m):
if grid[i][j] == "." and (
(i > 0 and grid[i - 1][j] == ".") or (j > 0 and grid[i][j - 1] == ".")
):
dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % mod
return dp[n - 1][m - 1]
n, m = list(map(int, input().split()))
grid = []
for i in range(n):
grid.append(input())
print(solve(n, m, grid))
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s958150754 | Runtime Error | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | # -*- coding: utf-8 -*-
#############
# Libraries #
#############
import sys
input = sys.stdin.readline
import math
# from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
#############
# Constants #
#############
MOD = 10**9 + 7
INF = float("inf")
AZ = "abcdefghijklmnopqrstuvwxyz"
#############
# Functions #
#############
######INPUT######
def I():
return int(input().strip())
def S():
return input().strip()
def IL():
return list(map(int, input().split()))
def SL():
return list(map(str, input().split()))
def ILs(n):
return list(int(input()) for _ in range(n))
def SLs(n):
return list(input().strip() for _ in range(n))
def ILL(n):
return [list(map(int, input().split())) for _ in range(n)]
def SLL(n):
return [list(map(str, input().split())) for _ in range(n)]
######OUTPUT######
def P(arg):
print(arg)
return
def Y():
print("Yes")
return
def N():
print("No")
return
def E():
exit()
def PE(arg):
print(arg)
exit()
def YE():
print("Yes")
exit()
def NE():
print("No")
exit()
#####Shorten#####
def DD(arg):
return defaultdict(arg)
#####Inverse#####
def inv(n):
return pow(n, MOD - 2, MOD)
######Combination######
kaijo_memo = []
def kaijo(n):
if len(kaijo_memo) > n:
return kaijo_memo[n]
if len(kaijo_memo) == 0:
kaijo_memo.append(1)
while len(kaijo_memo) <= n:
kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if len(gyaku_kaijo_memo) > n:
return gyaku_kaijo_memo[n]
if len(gyaku_kaijo_memo) == 0:
gyaku_kaijo_memo.append(1)
while len(gyaku_kaijo_memo) <= n:
gyaku_kaijo_memo.append(
gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo), MOD - 2, MOD) % MOD
)
return gyaku_kaijo_memo[n]
def nCr(n, r):
if n == r:
return 1
if n < r or r < 0:
return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n - r) % MOD
return ret
######Factorization######
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-(n**0.5) // 1)) + 1):
if temp % i == 0:
cnt = 0
while temp % i == 0:
cnt += 1
temp //= i
arr.append([i, cnt])
if temp != 1:
arr.append([temp, 1])
if arr == []:
arr.append([n, 1])
return arr
#####MakeDivisors######
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)
return divisors
#####MakePrimes######
def make_primes(N):
max = int(math.sqrt(N))
seachList = [i for i in range(2, N + 1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
return primeNum
#####GCD#####
def gcd(a, b):
while b:
a, b = b, a % b
return a
#####LCM#####
def lcm(a, b):
return a * b // gcd(a, b)
#####BitCount#####
def count_bit(n):
count = 0
while n:
n &= n - 1
count += 1
return count
#####ChangeBase#####
def base_10_to_n(X, n):
if X // n:
return base_10_to_n(X // n, n) + [X % n]
return [X % n]
def base_n_to_10(X, n):
return sum(int(str(X)[-i - 1]) * n**i for i in range(len(str(X))))
def base_10_to_n_without_0(X, n):
X -= 1
if X // n:
return base_10_to_n_without_0(X // n, n) + [X % n]
return [X % n]
#####IntLog#####
def int_log(n, a):
count = 0
while n >= a:
n //= a
count += 1
return count
#############
# Main Code #
#############
H, W = IL()
data = SLs(H)
dp = [[0 for i in range(W)] for j in range(H)]
dp[0][0] = 1
for j in range(1, H):
if data[j][0] != "#":
dp[j][0] = dp[j - 1][0]
for i in range(1, W):
if data[0][i] != "#":
dp[0][i] = dp[0][i - 1]
for j in range(1, H):
for i in range(1, W):
if data[i][j] != "#":
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
dp[i][j] %= MOD
print(dp[-1][-1])
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s670596971 | Runtime Error | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | h = int(input())
w = int(input())
grid = [int(i) for i in input().split()]
print("h", h)
print("w", w)
print("grid", grid)
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s203926967 | Runtime Error | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | v=pow(10,9)+7
arr=[]
inp = list(map(int,input().split()))
row=inp[0]
col=in[1]
for i in range(row):
s=input()
arr.append(s)
ans=[[0 for i in range(col)]for j in range(row)]
for i in range(col):
if arr[0][i]=='#':
break
else:
ans[0][i]=1
for i in range(row):
if arr[i][0]=='#':
break
else:
ans[i][0]=1
for i in range(1,row):
for j in range(1,col):
if arr[i][j]=='#':
continue
else:
arr[i][j]=(arr[i-1][j]+arr[i][j-1])%v
print (arr[-1][-1]) | Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s019029794 | Runtime Error | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | H, W = map(int, input().split())
field = [input() for i in range(H)]
route_count_memory = [[-1] * W for i in range(H)]
route_count_memory[0][0] = 1
def get_route_count(i, j):
result = 0
if route_count_memory[i][j] != -1:
return route_count_memory[i][j]
if 0 <= i - 1 < H and field[i - 1][j] != "#":
result += get_route_count(i - 1, j)
if 0 <= j - 1 < W and field[i][j - 1] != "#":
result += get_route_count(i, j - 1)
route_count_memory[i][j] = result
return result
print(get_route_count(H - 1, W - 1) % (10**9 + 7))
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s806895404 | Runtime Error | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | #include "bits/stdc++.h"
using namespace std;
using ll = long long; using ull = unsigned long long;
//#define int ll
using vb = vector<bool>; using vvb = vector<vb>;
using vi = vector<int>; using vvi = vector<vi>;
using vl = vector<ll>; using vvl = vector<vl>;
template<class T> using V = vector<T>;
template<class T> using vv = vector<V<T>>;
template<class T> using VV = vector<V<T>>;
#define fi first
#define se second
#define maxs(x,y) (x=max(x,y))
#define mins(x,y) (x=min(x,y))
using pii = pair<int,int>; using pll = pair<ll,ll>;
#define FOR(i,a,b) for(ll i = (a); i < (ll)(b); ++i)
#define REP(i,n) FOR(i,0,n)
#define RFOR(i,a,b) for(ll i = (ll)(b)-1;i >= a;--i)
#define RREP(i,n) RFOR(i,0,n)
#define ALL(obj) (obj).begin(), (obj).end()
#define rALL(obj) (obj).rbegin(), (obj).rend()
#define eb(val) emplace_back(val)
const double PI = acos(-1);
const double EPS = 1e-10;
const ll MOD = 1e9+7;
void cioacc(){//accelerate cin/cout
cin.tie(0);
ios::sync_with_stdio(false);
}
signed main(){
int h,w;
cin >> h >> w;
vector<string> mp(h);
REP(i,h) cin >> mp[i];
vvl dp(h,vl(w,0));
dp[0][0] = 1;
REP(i,w){
if(mp[0][i]=='#') break;
dp[0][i] = 1;
}
REP(i,h){
if(mp[i][0]=='#') break;
dp[i][0] = 1;
}
REP(i,h-1){
REP(j,w-1){
if(mp[i+1][j+1]=='#') continue;
dp[i+1][j+1] = (dp[i][j+1] + dp[i+1][j])%MOD;
}
}
cout << dp[h-1][w-1] << endl;
}
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 +
7.
* * * | s433452498 | Runtime Error | p03167 | Input is given from Standard Input in the following format:
H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W} | /*
Author:zeke
pass System Test!
GET AC!!
*/
#include <iostream>
#include <queue>
#include <vector>
#include <iostream>
#include <vector>
#include <string>
#include <cassert>
#include <algorithm>
#include <functional>
#include <cmath>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <map>
#include <iomanip>
#include <utility>
#include <stack>
using ll = long long;
using ld = long double;
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(), (x).end()
#define rep3(var, min, max) for (ll(var) = (min); (var) < (max); ++(var))
#define repi3(var, min, max) for (ll(var) = (max)-1; (var) + 1 > (min); --(var))
#define Mp(a, b) make_pair((a), (b))
#define F first
#define S second
#define Icin(s) \
ll(s); \
cin >> (s);
#define Scin(s) \
ll(s); \
cin >> (s);
template <class T>
bool chmax(T &a, const T &b)
{
if (a < b)
{
a = b;
return 1;
}
return 0;
}
template <class T>
bool chmin(T &a, const T &b)
{
if (b < a)
{
a = b;
return 1;
}
return 0;
}
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef vector<V> VV;
typedef vector<P> VP;
ll MOD = 1e9 + 7;
ll INF = 1e18;
vector<vector<int>> vec;
vector<vector<int>> dp;
int h, w;
void rec(int y, int x)
{
if (vec[y][x] == '#')
return; //壁だったら考えるまでもないです
if (y >= 1)
{
if (vec[y + 1][x] == '.')
{
dp[y][x] += dp[y - 1][x];
dp[y][x] %= MOD;
}
}
if (x >= 1)
{
if (vec[y][x] == '.')
{
dp[y][x] += dp[y][x - 1];
dp[y][x] %= MOD;
}
}
}
int main()
{
cin >> h >> w;
vec.resize(h, vector<int>(w));
dp.resize(h, vector<int>(w));
for (int i = 0; i < h; i++)
{
string s;
cin >> s;
for (int j = 0; j < w; j++)
{
vec[i][j] = s[j];
}
}
dp[0][0] = 1;
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
rec(i, j);
}
}
cout << dp[h - 1][w - 1] % MOD << endl;
}
| Statement
There is a grid with H horizontal rows and W vertical columns. Let (i, j)
denote the square at the i-th row from the top and the j-th column from the
left.
For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is
described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an
empty square; if a_{i, j} is `#`, Square (i, j) is a wall square. It is
guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right
or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W). As the answer
can be extremely large, find the count modulo 10^9 + 7. | [{"input": "3 4\n ...#\n .#..\n ....", "output": "3\n \n\nThere are three paths as follows:\n\n\n\n* * *"}, {"input": "5 2\n ..\n #.\n ..\n .#\n ..", "output": "0\n \n\nThere may be no paths.\n\n* * *"}, {"input": "5 5\n ..#..\n .....\n #...#\n .....\n ..#..", "output": "24\n \n\n* * *"}, {"input": "20 20\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................\n ....................", "output": "345263555\n \n\nBe sure to print the count modulo 10^9 + 7."}] |
Print 2^N lines. The (i+1)-th line (0 \leq i \leq 2^N-1) should contain the
expected number of operations until X becomes i, modulo 998244353.
* * * | s831677343 | Runtime Error | p03022 | Input is given from Standard Input in the following format:
N
A_0 A_1 \cdots A_{2^N-1} | import sys
sys.setrecursionlimit(10000)
input = sys.stdin.readline
def g(l):
if not l:
return 0, 0
m, s = max(l), sum(l)
if 2 * m > s:
return 2 * m - s, (s - m)
return s % 2, s // 2
def f(v, vs):
ks = []
r = 0
rkoma = 0
for u in d[v]:
if u in vs:
continue
vs.add(u)
k1, k2, koma = f(u, vs)
ks.append(k1)
rkoma += koma
r += k2
r1, r2 = g(ks)
# r1 深さの和、r2 操作の回数
rkoma += km[v]
# print(v, r1 + rkoma, r + r2, rkoma)
return r1 + rkoma, r + r2, rkoma
N = int(input())
km = [0] + [int(i) for i in str(input().strip())]
d = [set() for _ in range(N + 1)]
for _ in range(N - 1):
x, y = map(int, input().split())
d[x].add(y)
d[y].add(x)
r = 10**10
for i in range(N):
a, b, c = f(i + 1, {i + 1})
if a == c:
r = min(r, b)
print(r if r != 10**10 else -1)
| Statement
Snuke found a random number generator. It generates an integer between 0 and
2^N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents
the probability that each of these integers is generated. The integer i (0
\leq i \leq 2^N-1) is generated with probability A_i / S, where S =
\sum_{i=0}^{2^N-1} A_i. The process of generating an integer is done
independently each time the generator is executed.
Snuke has an integer X, which is now 0. He can perform the following operation
any number of times:
* Generate an integer v with the generator and replace X with X \oplus v, where \oplus denotes the bitwise XOR.
For each integer i (0 \leq i \leq 2^N-1), find the expected number of
operations until X becomes i, and print it modulo 998244353. More formally,
represent the expected number of operations as an irreducible fraction P/Q.
Then, there exists a unique integer R such that R \times Q \equiv P \mod
998244353,\ 0 \leq R < 998244353, so print this R.
We can prove that, for every i, the expected number of operations until X
becomes i is a finite rational number, and its integer representation modulo
998244353 can be defined. | [{"input": "2\n 1 1 1 1", "output": "0\n 4\n 4\n 4\n \n\nX=0 after zero operations, so the expected number of operations until X\nbecomes 0 is 0.\n\nAlso, from any state, the value of X after one operation is 0, 1, 2 or 3 with\nequal probability. Thus, the expected numbers of operations until X becomes 1,\n2 and 3 are all 4.\n\n* * *"}, {"input": "2\n 1 2 1 2", "output": "0\n 499122180\n 4\n 499122180\n \n\nThe expected numbers of operations until X becomes 0, 1, 2 and 3 are 0, 7/2, 4\nand 7/2, respectively.\n\n* * *"}, {"input": "4\n 337 780 799 10 796 875 331 223 941 67 148 483 390 565 116 355", "output": "0\n 468683018\n 635850749\n 96019779\n 657074071\n 24757563\n 745107950\n 665159588\n 551278361\n 143136064\n 557841197\n 185790407\n 988018173\n 247117461\n 129098626\n 789682908"}] |
Print 2^N lines. The (i+1)-th line (0 \leq i \leq 2^N-1) should contain the
expected number of operations until X becomes i, modulo 998244353.
* * * | s968921109 | Wrong Answer | p03022 | Input is given from Standard Input in the following format:
N
A_0 A_1 \cdots A_{2^N-1} | print("wakaranai")
| Statement
Snuke found a random number generator. It generates an integer between 0 and
2^N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents
the probability that each of these integers is generated. The integer i (0
\leq i \leq 2^N-1) is generated with probability A_i / S, where S =
\sum_{i=0}^{2^N-1} A_i. The process of generating an integer is done
independently each time the generator is executed.
Snuke has an integer X, which is now 0. He can perform the following operation
any number of times:
* Generate an integer v with the generator and replace X with X \oplus v, where \oplus denotes the bitwise XOR.
For each integer i (0 \leq i \leq 2^N-1), find the expected number of
operations until X becomes i, and print it modulo 998244353. More formally,
represent the expected number of operations as an irreducible fraction P/Q.
Then, there exists a unique integer R such that R \times Q \equiv P \mod
998244353,\ 0 \leq R < 998244353, so print this R.
We can prove that, for every i, the expected number of operations until X
becomes i is a finite rational number, and its integer representation modulo
998244353 can be defined. | [{"input": "2\n 1 1 1 1", "output": "0\n 4\n 4\n 4\n \n\nX=0 after zero operations, so the expected number of operations until X\nbecomes 0 is 0.\n\nAlso, from any state, the value of X after one operation is 0, 1, 2 or 3 with\nequal probability. Thus, the expected numbers of operations until X becomes 1,\n2 and 3 are all 4.\n\n* * *"}, {"input": "2\n 1 2 1 2", "output": "0\n 499122180\n 4\n 499122180\n \n\nThe expected numbers of operations until X becomes 0, 1, 2 and 3 are 0, 7/2, 4\nand 7/2, respectively.\n\n* * *"}, {"input": "4\n 337 780 799 10 796 875 331 223 941 67 148 483 390 565 116 355", "output": "0\n 468683018\n 635850749\n 96019779\n 657074071\n 24757563\n 745107950\n 665159588\n 551278361\n 143136064\n 557841197\n 185790407\n 988018173\n 247117461\n 129098626\n 789682908"}] |
Output should be in the following format:
n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}
n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the
color for the square (r, c).
* * * | s814583449 | Wrong Answer | p03188 | Input is given from Standard Input in the following format:
K | n = int(input())
print(n)
for i in range(n):
print(*list(range(1, 1 + n)))
| Statement
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from
the top and the (c+1)-th column from the left. A _good_ coloring of this grid
using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).
Given K, choose **n between 1 and 500** (inclusive) freely and construct a
good coloring of an n \times n grid using K colors. It can be proved that this
is always possible under the constraints of this problem, | [{"input": "2", "output": "3\n 1 1 1\n 1 1 1\n 2 2 2\n \n\n * Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.\n * Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.\n\nOutput such as the following will be judged incorrect:\n\n \n \n 2\n 1 2\n 2 2\n \n \n \n 3\n 1 1 1\n 1 1 1\n 1 1 1\n \n\n* * *"}, {"input": "9", "output": "3\n 1 2 3\n 4 5 6\n 7 8 9"}] |
Output should be in the following format:
n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}
n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the
color for the square (r, c).
* * * | s215232514 | Wrong Answer | p03188 | Input is given from Standard Input in the following format:
K | k = int(input())
n = k
if k <= 500:
print(n)
ans = []
for i in range(n):
ans.append([i + 1] * n)
for i in ans:
print(*i)
else:
if k % 2 == 0:
n2 = n // 2
flag = 0
if n2 % 2 == 1:
n2 += 1
flag = 1
print(n2)
ans = []
for i in range(n2):
tmp = []
for j in range(n2):
if j % 2 == 0:
tmp.append(i * 2 + 1)
else:
tmp.append(i * 2 + 2)
ans.append(tmp)
if flag:
ans.pop()
ans.pop()
ans.append([k - 1] * n2)
ans.append([k] * n2)
for i in ans:
print(*i)
else:
n2 = n // 2 + 1
flag = 0
if n2 % 2 == 1:
n2 += 1
flag = 1
print(n2)
ans = []
for i in range(n2 - 1):
tmp = []
for j in range(n2):
if j % 2 == 0:
tmp.append(i * 2 + 1)
else:
tmp.append(i * 2 + 2)
ans.append(tmp)
ans.append([k] * (n // 2 + 1))
if flag:
ans.pop()
ans.pop()
ans.pop()
ans.append([k - 2] * n2)
ans.append([k - 1] * n2)
ans.append([k] * n2)
for i in ans:
print(*i)
| Statement
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from
the top and the (c+1)-th column from the left. A _good_ coloring of this grid
using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).
Given K, choose **n between 1 and 500** (inclusive) freely and construct a
good coloring of an n \times n grid using K colors. It can be proved that this
is always possible under the constraints of this problem, | [{"input": "2", "output": "3\n 1 1 1\n 1 1 1\n 2 2 2\n \n\n * Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.\n * Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.\n\nOutput such as the following will be judged incorrect:\n\n \n \n 2\n 1 2\n 2 2\n \n \n \n 3\n 1 1 1\n 1 1 1\n 1 1 1\n \n\n* * *"}, {"input": "9", "output": "3\n 1 2 3\n 4 5 6\n 7 8 9"}] |
Output should be in the following format:
n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}
n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the
color for the square (r, c).
* * * | s581301179 | Wrong Answer | p03188 | Input is given from Standard Input in the following format:
K | N = int(input())
if N <= 500:
A = []
for i in range(N):
a = []
for j in range(N):
a.append(i + 1)
A.append(a)
print(N)
for i in range(N):
ans = ""
for j in range(N):
ans += str(A[i][j]) + " "
print(ans)
else:
A = []
for i in range(34):
a = []
for j in range(68):
a.append((i * 34 + j) // 2 + 1)
A.append(a)
A.append(a)
print(68)
for i in range(68):
ans = ""
for j in range(68):
ans += str(A[i][j]) + " "
print(ans)
| Statement
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from
the top and the (c+1)-th column from the left. A _good_ coloring of this grid
using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).
Given K, choose **n between 1 and 500** (inclusive) freely and construct a
good coloring of an n \times n grid using K colors. It can be proved that this
is always possible under the constraints of this problem, | [{"input": "2", "output": "3\n 1 1 1\n 1 1 1\n 2 2 2\n \n\n * Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.\n * Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.\n\nOutput such as the following will be judged incorrect:\n\n \n \n 2\n 1 2\n 2 2\n \n \n \n 3\n 1 1 1\n 1 1 1\n 1 1 1\n \n\n* * *"}, {"input": "9", "output": "3\n 1 2 3\n 4 5 6\n 7 8 9"}] |
Output should be in the following format:
n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}
n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the
color for the square (r, c).
* * * | s502357461 | Runtime Error | p03188 | Input is given from Standard Input in the following format:
K | l, n = map(int, input().split())
c = n
tree = [int(input()) for i in range(n)]
reversed_tree = [l - i for i in reversed(tree)]
if n % 2 == 0:
ans = sum(tree) * 2 + l * (n - 1) + tree[n // 2] - sum(tree[n // 2 :]) * 4
ans2 = (
sum(reversed_tree) * 2
+ l * (n - 1)
+ reversed_tree[n // 2]
- sum(reversed_tree[n // 2 :]) * 4
)
n -= 1
c -= 1
ans = max(ans, ans - tree.pop(0) * 2 - l + tree[n // 2] * 2)
ans2 = max(ans2, ans2 - reversed_tree.pop(0) * 2 - l + reversed_tree[n // 2] * 2)
else:
ans = sum(tree) * 2 + l * (n - 1) - tree[n // 2] - sum(tree[(n // 2 + 1) :]) * 4
ans2 = (
sum(reversed_tree) * 2
+ l * (n - 1)
- reversed_tree[n // 2]
- sum(reversed_tree[(n // 2 + 1) :]) * 4
)
while n > 1:
n -= 1
ans = max(ans, ans - tree.pop(0) * 2 - l + tree[(n - 1) // 2] + tree[(n + 1) // 2])
n -= 1
ans = max(ans, ans - tree.pop(0) * 2 - l + tree[n // 2] * 2)
n = c
while n > 1:
n -= 1
ans2 = max(
ans2,
ans2
- reversed_tree.pop(0) * 2
- l
+ reversed_tree[(n - 1) // 2]
+ reversed_tree[(n + 1) // 2],
)
n -= 1
ans2 = max(ans2, ans2 - reversed_tree.pop(0) * 2 - l + reversed_tree[n // 2] * 2)
print(max(ans, ans2))
| Statement
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from
the top and the (c+1)-th column from the left. A _good_ coloring of this grid
using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).
Given K, choose **n between 1 and 500** (inclusive) freely and construct a
good coloring of an n \times n grid using K colors. It can be proved that this
is always possible under the constraints of this problem, | [{"input": "2", "output": "3\n 1 1 1\n 1 1 1\n 2 2 2\n \n\n * Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.\n * Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.\n\nOutput such as the following will be judged incorrect:\n\n \n \n 2\n 1 2\n 2 2\n \n \n \n 3\n 1 1 1\n 1 1 1\n 1 1 1\n \n\n* * *"}, {"input": "9", "output": "3\n 1 2 3\n 4 5 6\n 7 8 9"}] |
Output should be in the following format:
n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}
n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the
color for the square (r, c).
* * * | s203457463 | Wrong Answer | p03188 | Input is given from Standard Input in the following format:
K | k = int(input())
if k <= 500:
print(k)
for i in range(k):
print([(i + 1)] * k)
| Statement
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from
the top and the (c+1)-th column from the left. A _good_ coloring of this grid
using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).
Given K, choose **n between 1 and 500** (inclusive) freely and construct a
good coloring of an n \times n grid using K colors. It can be proved that this
is always possible under the constraints of this problem, | [{"input": "2", "output": "3\n 1 1 1\n 1 1 1\n 2 2 2\n \n\n * Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.\n * Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.\n\nOutput such as the following will be judged incorrect:\n\n \n \n 2\n 1 2\n 2 2\n \n \n \n 3\n 1 1 1\n 1 1 1\n 1 1 1\n \n\n* * *"}, {"input": "9", "output": "3\n 1 2 3\n 4 5 6\n 7 8 9"}] |
Output should be in the following format:
n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}
n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the
color for the square (r, c).
* * * | s625535391 | Runtime Error | p03188 | Input is given from Standard Input in the following format:
K | K = int(input())
n = 0
n1 = 0
n2 = 0
n3 = 0
n4 = 0
n5 = 0
#Kが500以下の場合、斜め作戦にする
if K <= 500:
n = K
mat = [[0 for n1 in range(K)] for n2 in range(K)]
for n1 in range(K):
for n2 in range(K-n1):
mat[n1][n1+n2] = n2+1
for n1 in range(K):
for n2 in range(n1):
mat[n1][n2] = K+n2-n1+1
#Kが500以上の場合、斜めに1マスずつしのびこませる
else:
n = 500
mat = [[0 for n1 in range(500)] for n2 in range(500)]
for n1 in range(500):
for n2 in range(500-n1):
mat[n1][n1+n2] = n2+1
for n1 in range(500):
for n2 in range(n1):
mat[n1][n2] = 500+n2-n1+1
#行列の出力かんがえとく
print(n)
if K <= 500:
out = ""
for n1 in range(K):
out = ""
for n2 in range(K):
out = out + " " + str(mat[n1][n2])
print(out)
#Kが500以上の場合、斜めに1マスずつしのびこませる
else:
out = ""
for n1 in range(500):
out = ""
for n2 in range(500):
out = out + " " + str(mat[n1][n2])
print(out)
| Statement
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from
the top and the (c+1)-th column from the left. A _good_ coloring of this grid
using K colors is a coloring that satisfies the following:
* Each square is painted in one of the K colors.
* Each of the K colors is used for some squares.
* Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).
Given K, choose **n between 1 and 500** (inclusive) freely and construct a
good coloring of an n \times n grid using K colors. It can be proved that this
is always possible under the constraints of this problem, | [{"input": "2", "output": "3\n 1 1 1\n 1 1 1\n 2 2 2\n \n\n * Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.\n * Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.\n\nOutput such as the following will be judged incorrect:\n\n \n \n 2\n 1 2\n 2 2\n \n \n \n 3\n 1 1 1\n 1 1 1\n 1 1 1\n \n\n* * *"}, {"input": "9", "output": "3\n 1 2 3\n 4 5 6\n 7 8 9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s475092609 | Wrong Answer | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | # -*- coding: utf-8 -*-
import sys
def main():
N, H = map(int, input().split(" "))
turn = 0
atk = []
doit = []
atk_max = 0
doit_max = 0
doit_total = 0
for _ in range(N):
a, b = map(int, input().split(" "))
doit_total += b
if atk_max < a:
atk_max = a
atk.append(a)
doit.append(b)
if doit_total >= H:
print(len(doit))
atk_max_i = []
for i, val in enumerate(atk):
if atk_max == val:
atk_max_i.append(i)
if len(atk_max_i) > 1:
dels = []
for i, val in enumerate(atk_max_i):
if i == 0:
continue
if doit[atk_max_i[i - 1]] > doit[atk_max_i[i]]:
H -= doit[atk_max_i[i - 1]]
dels.append(atk_max_i[i - 1])
else:
H -= doit[atk_max_i[i]]
dels.append(atk_max_i[i])
turn += 1
for i, val in enumerate(dels):
del atk[val - i]
del doit[val - i]
if len(doit) == 1:
doit_max = doit[0]
for i, val in enumerate(doit):
if atk_max < val:
if atk[i] != atk_max:
H -= val
turn += 1
else:
doit_max = val
on = H // atk_max
if doit_max - atk_max >= H % atk_max:
print(turn + on)
else:
print(turn + on + 1)
if __name__ == "__main__":
main()
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s821650400 | Accepted | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10**7)
# UnionFind
class UnionFind:
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return "\n".join("{}: {}".format(r, self.members(r)) for r in self.roots())
def is_prime(n):
if n == 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
# d[i][j]: iからjへの最短距離
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d
# ダイクストラ
def dijkstra_heap(s, edge, n):
# 始点sから各頂点への最短距離
d = [10**20] * n
used = [True] * n # True:未確定
d[s] = 0
used[s] = False
edgelist = []
for a, b in edge[s]:
heapq.heappush(edgelist, a * (10**6) + b)
while len(edgelist):
minedge = heapq.heappop(edgelist)
# まだ使われてない頂点の中から最小の距離のものを探す
if not used[minedge % (10**6)]:
continue
v = minedge % (10**6)
d[v] = minedge // (10**6)
used[v] = False
for e in edge[v]:
if used[e[1]]:
heapq.heappush(edgelist, (e[0] + d[v]) * (10**6) + e[1])
return d
# 素因数分解
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-(n**0.5) // 1)) + 1):
if temp % i == 0:
cnt = 0
while temp % i == 0:
cnt += 1
temp //= i
arr.append([i, cnt])
if temp != 1:
arr.append([temp, 1])
if arr == []:
arr.append([n, 1])
return arr
# 2数の最小公倍数
def lcm(x, y):
return (x * y) // gcd(x, y)
# リストの要素の最小公倍数
def lcm_list(numbers):
return reduce(lcm, numbers, 1)
# リストの要素の最大公約数
def gcd_list(numbers):
return reduce(gcd, numbers)
# 素数判定
# limit以下の素数を列挙
def eratosthenes(limit):
A = [i for i in range(2, limit + 1)]
P = []
while True:
prime = min(A)
if prime > sqrt(limit):
break
P.append(prime)
i = 0
while i < len(A):
if A[i] % prime == 0:
A.pop(i)
continue
i += 1
for a in A:
P.append(a)
return P
# 同じものを含む順列
def permutation_with_duplicates(L):
if L == []:
return [[]]
else:
ret = []
# set(集合)型で重複を削除、ソート
S = sorted(set(L))
for i in S:
data = L[:]
data.remove(i)
for j in permutation_with_duplicates(data):
ret.append([i] + j)
return ret
# ここから書き始める
n, h = map(int, input().split())
b = [0 for i in range(n)]
a_max = 0
for i in range(n):
c, d = map(int, input().split())
a_max = max(a_max, c)
b[i] = d
b.sort(reverse=True)
for i in range(1, n):
b[i] += b[i - 1]
if a_max >= h or b[0] >= h:
print(1)
else:
ans = -(-h // a_max)
for i in range(n):
if b[i] >= h:
ans = min(ans, i + 1)
break
ans = min(ans, i + 1 - (-(h - b[i]) // a_max))
print(ans)
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s784996419 | Wrong Answer | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | n, h, *L = map(int, open(0).read().split())
a = max(L[::2])
print(len(b := [l for l in L[1::2] if l > a]) - ((sum(b) - h) // a))
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s174895935 | Accepted | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | # -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
class Scanner:
@staticmethod
def int():
return int(sys.stdin.readline().rstrip())
@staticmethod
def string():
return sys.stdin.readline().rstrip()
@staticmethod
def map_int():
return [int(x) for x in Scanner.string().split()]
@staticmethod
def string_list(n):
return [input() for i in range(n)]
@staticmethod
def int_list_list(n):
return [Scanner.map_int() for i in range(n)]
@staticmethod
def int_cols_list(n):
return [int(input()) for i in range(n)]
class Math:
@staticmethod
def gcd(a, b):
if b == 0:
return a
return Math.gcd(b, a % b)
@staticmethod
def lcm(a, b):
return (a * b) // Math.gcd(a, b)
@staticmethod
def roundUp(a, b):
return -(-a // b)
@staticmethod
def toUpperMultiple(a, x):
return Math.roundUp(a, x) * x
@staticmethod
def toLowerMultiple(a, x):
return (a // x) * x
@staticmethod
def nearPow2(n):
if n <= 0:
return 0
if n & (n - 1) == 0:
return n
ret = 1
while n > 0:
ret <<= 1
n >>= 1
return ret
@staticmethod
def sign(n):
if n == 0:
return 0
if n < 0:
return -1
return 1
@staticmethod
def isPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
d = int(n**0.5) + 1
for i in range(3, d + 1, 2):
if n % i == 0:
return False
return True
MOD = int(1e09) + 7
INF = int(1e15)
def main():
# sys.stdin = open("sample.txt")
N, H = Scanner.map_int()
A = [0] * N
B = [0] * N
for i in range(N):
a, b = Scanner.map_int()
A[i] = a
B[i] = b
A.sort(reverse=True)
B.sort(reverse=True)
ans = 0
for i in range(N):
if B[i] > A[0]:
ans += 1
H -= B[i]
if H <= 0:
break
else:
break
H = max(0, H)
ans += Math.roundUp(H, A[0])
print(ans)
if __name__ == "__main__":
main()
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s210353587 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | n,h=map(int,input().split())
ab=[[int(i) for i in input().split()] for _ in range(n)]
maxa=max(map(lambda x:x[0], ab))
ab.sort(key:lambda x:x[1],reverse=True)
ans=0
for a,b in ab:
if b>maxa:
h-=b
ans+=1
if h<=0:
print(ans)
exit(0)
print(ans+(h-1)//maxa+1) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s456197447 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | n,h=map(int,input().split())
a=[0]*n
b=[0]*n
for i in range(n)
a[i],b[i]=map(int,input().split())
x=max((a))
y=[i for i in b if i>A]
y.sort(reverse=True)
count=0
for i in range(len(y)):
if h>0:
count+=1
h-=y[i]
else:
break
if h>0:
count +=int(h//x)+1
print(count) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s780230784 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | n, h = map(int, input().split())
a = []
b = []
amax = 0
for i in range(n):
ai, bi = map(int, input().split())
if amax < ai:
amax = ai
a.append(ai)
b.append(bi)
b = [b[j] for j in range(n) if b[j] > amax]
sumb = sum(b)
if sumb >= h:
s = 0
b = sorted(b)
c = 0
while s < h:
s += b[-1]
b.pop(-1)
c + =1
print(c)
else:
print((h-sumb)//amax+((h-sumb)%amax!=0) + len(b))
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s479667091 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | port numpy as np
N, H = map(int,input().split())
maxA = 0
B = []
for _ in range(N):
a, b = map(int,input().split())
B.append(b)
if maxA < a:
maxA = a
B = np.array(B)
throw_all = np.sort((B[B>maxA]))
SUM = 0
cnt = 0
print(throw_all)
for a in throw_all:
SUM += a
cnt += 1
if SUM >= H:
print(cnt)
exit()
ans = -(-(H-SUM)//maxA)+ cnt
print(ans)
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s649463708 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | import math as m1
n, h = map(int, input().split())
a, b = [], []
for i in range(n):
a_, b_ = map(int, input().split())
a.append(a_)
b.append(b_)
b = list(reversed(sorted(b)))
m = max(a)
ans = 0
for i in b:
if i > m:
if h - i <= 0:
print(ans + 1)
exit()
h -= i
ans += 1
if
print(ans + m1.ceil(h / m)) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s537767066 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | N,H=map(int,input().split())
a=[0]*N
b=[0]*N
for i in range(N):
a[i],b[i]=map(int,input().split())
amax=max(a)
n=0
total=0
b.sort(reverse=True)
for i in range(N):
if b[i] > amax:
n+=1
total+=b[i]
else:
break
if H <= total:
for i in range(n):
H-=b[i]
if H <=0:
print(i+1)
break
else:
print(n+int((H-total-1)/amax)+1) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s445004544 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | using System;
using System.Linq;
using System.Collections.Generic;
namespace Algorithm
{
class Program
{
static void Main(string[] args)
{
var l = Console.ReadLine().Split().Select(int.Parse).ToArray();
int n = l[0], h = l[1];
var ab = new int[n][];
for (var i = 0; i < n; i++)
ab[i] = Console.ReadLine().Split().Select(int.Parse).ToArray();
var maxA = ab.Max(x => x[0]);
var minB = ab.Where(w => w[0] == maxA).Min(x => x[1]);
var count = 0L;
foreach (var val in ab.OrderByDescending(o => o[1]).ToArray())
{
count++;
if (maxA < val[1] && maxA != val[0]) h -= val[1];
else
{
h -= val[1];
if (h > 0 && minB == val[1])
{
count += h % val[0] == 0 ? h / val[0] : h / val[0] + 1;
break;
}
}
if (h <= 0) break;
}
Console.WriteLine(count);
}
}
}
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s788327194 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | n,h=map(int,input().split())
a=[]
for i in range(n):
b,c=map(int,input().split())
a.append([b,0]);a.append([c,1])
a.sort(reverse=1)
i=0
ans=0
while h>0:
if a[i][1]==1:h-=a[i][0];ans+=1
else h=0:ans+=(h-1)//a[i][0]+1
print(ans) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s592882395 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | import math
count = 0
n, h = map(int, input().split(' '))
ab = [input().split(' ') for _ in range(n)]
max_a = int(sorted(ab, key=lambda x: int(x[0]), reverse=True)[0][0])
for x in ab:
if int(x[1]) >= max_a:
h -= int(x[1])
count += 1
count += math.ceil((h / max_a)
print(count) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s499561240 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | %%test_input https://atcoder.jp/contests/abc085/tasks/abc085_d
# D
import math
n, h = map(int, input().split())
max_a = 0
a = [0] * n
b = [0] * n
for i in range(n):
a[i], b[i] = map(int, input().split())
if max_a < a[i]:
max_a = a[i]
throw = []
for i in range(n):
if b[i] > max_a:
throw.append(b[i])
throw.sort(reverse=True)
damage = 0
count = 0
for i in range(len(throw)):
damage += throw[i]
count += 1
if damage >= h:
break
if damage < h:
count += math.ceil((h - damage) / max_a)
print(count) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s011572959 | Runtime Error | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | import sys
N,H=map(int,input().split())
B=[]
index=-1
tmp=-1
for i in range(N):
a,b=map(int,input().split())
B.append(b)
if a>tmp:
index=i
tmp=a
a_,b_=tmp,B[index]
cnt=0
if sum(B)>=H:
B=sorted(B,reverse=True)
while H>0:
cnt+=1
b=B.pop(0)
H-=b
print(cnt)
else:
B.remove(b_)
B=sorted(B,reverse=True)
while len(B)!=0 :
b=B.pop(0)
if b<=a_:
break
H-=b
cnt+=1
if H-b_<=0:
print(cnt+1)
sys.exit()
v=(H-b_)//a_
cnt+=v
H-=a_*v
if 0=<H<=b_:
cnt+=1
else:
cnt+=2
print(cnt) | Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
Print the minimum total number of attacks required to vanish the monster.
* * * | s911185006 | Wrong Answer | p03472 | Input is given from Standard Input in the following format:
N H
a_1 b_1
:
a_N b_N | import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians
sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9 + 7
def lcm(x, y):
return x * y // gcd(x, y)
def lgcd(l):
return reduce(gcd, l)
def llcm(l):
return reduce(lcm, l)
def powmod(n, i, mod):
return pow(n, mod - 1 + i, mod) if i < 0 else pow(n, i, mod)
def div2(x):
return x.bit_length()
def div10(x):
return len(str(x)) - (x == 0)
def intput():
return int(input())
def mint():
return map(int, input().split())
def lint():
return list(map(int, input().split()))
def ilint():
return int(input()), list(map(int, input().split()))
def judge(x, l=["Yes", "No"]):
print(l[0] if x else l[1])
def lprint(l, sep="\n"):
for x in l:
print(x, end=sep)
def ston(c, c0="a"):
return ord(c) - ord(c0)
def ntos(x, c0="a"):
return chr(x + ord(c0))
class counter(dict):
def __init__(self, *args):
super().__init__(args)
def add(self, x, d=1):
self.setdefault(x, 0)
self[x] += d
def list(self):
l = []
for k in self:
l.extend([k] * self[k])
return l
class comb:
def __init__(self, n, mod=None):
self.l = [1]
self.n = n
self.mod = mod
def get(self, k):
l, n, mod = self.l, self.n, self.mod
k = n - k if k > n // 2 else k
while len(l) <= k:
i = len(l)
l.append(
l[i - 1] * (n + 1 - i) // i
if mod == None
else (l[i - 1] * (n + 1 - i) * powmod(i, -1, mod)) % mod
)
return l[k]
def pf(x):
C = counter()
p = 2
while x > 1:
k = 0
while x % p == 0:
x //= p
k += 1
if k > 0:
C.add(p, k)
p = p + 2 - (p == 2) if p * p < x else x
return C
N, H = mint()
L = []
for _ in range(N):
L.append(lint())
L.sort(key=lambda x: x[0])
L.sort(reverse=True, key=lambda x: x[1])
b0 = sum([x[1] for x in L])
AB = []
tmp = 0
k = N
for a, b in L[::-1]:
tmp = max(a, tmp)
AB.append([tmp, b0, k])
b0 -= b
k -= 1
ans = INF
for a, b, k in AB:
ans = min(ans, max(0, (H - b - 1) // a + 1) + k)
print(ans)
| Statement
You are going out for a walk, when you suddenly encounter a monster.
Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and
can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.
* Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.
The monster will vanish when the total damage it has received is H points or
more. At least how many attacks do you need in order to vanish it in total? | [{"input": "1 10\n 3 5", "output": "3\n \n\nYou have one katana. Wielding it deals 3 points of damage, and throwing it\ndeals 5 points of damage. By wielding it twice and then throwing it, you will\ndeal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing\nthe monster.\n\n* * *"}, {"input": "2 10\n 3 5\n 2 6", "output": "2\n \n\nIn addition to the katana above, you also have another katana. Wielding it\ndeals 2 points of damage, and throwing it deals 6 points of damage. By\nthrowing both katana, you will deal 5 + 6 = 11 points of damage in two\nattacks, vanishing the monster.\n\n* * *"}, {"input": "4 1000000000\n 1 1\n 1 10000000\n 1 30000000\n 1 99999999", "output": "860000004\n \n\n* * *"}, {"input": "5 500\n 35 44\n 28 83\n 46 62\n 31 79\n 40 43", "output": "9"}] |
If all N participants can communicate with all other participants, print
`YES`. Otherwise, print `NO`.
* * * | s746102025 | Runtime Error | p03921 | The input is given from Standard Input in the following format:
N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N} | import sys
sys.setrecursionlimit(10**6)
n,m=map(int,input().split())
a=[[]for i in range(n+m)]
for i in range(n):
s=list(map(int,input().split()))
for j in s[1:]:
a[i].append(j)
a[n+j].append(i)
t=[False]*n
def g(x):
if not t[x]:
t[x]=False:
for i in a[x]:
for j in a[i+n]:
g(j)
g(0)
if all(t):
print("YES")
else:
print("NO") | Statement
On a planet far, far away, M languages are spoken. They are conveniently
numbered 1 through M.
For _CODE FESTIVAL 20XX_ held on this planet, N participants gathered from all
over the planet.
The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1},
L_{i,2}, ..., L_{i,{}K_i}.
Two participants A and B can _communicate_ with each other if and only if one
of the following conditions is satisfied:
* There exists a language that both A and B can speak.
* There exists a participant X that both A and B can communicate with.
Determine whether all N participants can communicate with all other
participants. | [{"input": "4 6\n 3 1 2 3\n 2 4 2\n 2 4 6\n 1 6", "output": "YES\n \n\nAny two participants can communicate with each other, as follows:\n\n * Participants 1 and 2: both can speak language 2.\n * Participants 2 and 3: both can speak language 4.\n * Participants 1 and 3: both can communicate with participant 2.\n * Participants 3 and 4: both can speak language 6.\n * Participants 2 and 4: both can communicate with participant 3.\n * Participants 1 and 4: both can communicate with participant 2.\n\nNote that there can be languages spoken by no participant.\n\n* * *"}, {"input": "4 4\n 2 1 2\n 2 1 2\n 1 3\n 2 4 3", "output": "NO\n \n\nFor example, participants 1 and 3 cannot communicate with each other."}] |
If all N participants can communicate with all other participants, print
`YES`. Otherwise, print `NO`.
* * * | s213829690 | Runtime Error | p03921 | The input is given from Standard Input in the following format:
N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N} | class UnionFind:
def __init__(self, n):
self.n = n
self.p = [e for e in range(n)]
self.rank = [0] * n
self.size = [1] * n
def same(self, u, v):
return self.find_set(u) == self.find_set(v)
def unite(self, u, v):
u = self.find_set(u)
v = self.find_set(v)
if u == v:
return
if self.rank[u] > self.rank[v]:
self.p[v] = u
self.size[u] += self.size[v]
else:
self.p[u] = v
self.size[v] += self.size[u]
if self.rank[u] == self.rank[v]:
self.rank[v] += 1
def find_set(self, u):
if u != self.p[u]:
self.p[u] = self.find_set(self.p[u])
return self.p[u]
def update_p(self):
for u in range(self.n):
self.find_set(u)
def get_size(self, u):
return self.size[self.find_set(u)]
n, m = map(int, input().split())
l = []
for _ in range(n):
k, *ls = map(int, input().split())
l.append(ls)
uf = UnionFind(m)
for li in l:
for e1, e2 in zip(li, li[1:]):
e1 -= 1
e2 -= 1
uf.unite(e1, e2)
p = uf.find_set(l[0][0])
ans = "YES"
for e, *_ in l:
e -= 1
if uf.find_set(e) != p:
ans = "NO"
print(ans)
| Statement
On a planet far, far away, M languages are spoken. They are conveniently
numbered 1 through M.
For _CODE FESTIVAL 20XX_ held on this planet, N participants gathered from all
over the planet.
The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1},
L_{i,2}, ..., L_{i,{}K_i}.
Two participants A and B can _communicate_ with each other if and only if one
of the following conditions is satisfied:
* There exists a language that both A and B can speak.
* There exists a participant X that both A and B can communicate with.
Determine whether all N participants can communicate with all other
participants. | [{"input": "4 6\n 3 1 2 3\n 2 4 2\n 2 4 6\n 1 6", "output": "YES\n \n\nAny two participants can communicate with each other, as follows:\n\n * Participants 1 and 2: both can speak language 2.\n * Participants 2 and 3: both can speak language 4.\n * Participants 1 and 3: both can communicate with participant 2.\n * Participants 3 and 4: both can speak language 6.\n * Participants 2 and 4: both can communicate with participant 3.\n * Participants 1 and 4: both can communicate with participant 2.\n\nNote that there can be languages spoken by no participant.\n\n* * *"}, {"input": "4 4\n 2 1 2\n 2 1 2\n 1 3\n 2 4 3", "output": "NO\n \n\nFor example, participants 1 and 3 cannot communicate with each other."}] |
If all N participants can communicate with all other participants, print
`YES`. Otherwise, print `NO`.
* * * | s694586040 | Wrong Answer | p03921 | The input is given from Standard Input in the following format:
N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N} | import sys
import numpy as np
# f = open("input.txt")
f = input()
NM = f.split(" ")
N = int(NM[0])
M = int(NM[1])
K = []
L = []
for i in range(N):
line = input().rstrip("\n").split(" ")
K.append(int(line[0]))
L.append(set(line[1:]))
# print(line)
# print(K)
# print(L)
while True:
tmp = L
for x in range(len(L)):
for y in range(x + 1, len(L)):
if x == y:
continue
if list(L[x] & L[y]) != []:
L[x] = L[y] = L[x] | L[y]
# print(L)
if tmp == L:
break
flag = True
comp = L[0]
for l in L:
if list(comp ^ l) != []:
flag = False
break
if flag:
print("YES")
else:
print("NO")
# for n in out:
# print(n)
# print(' '.join(map(str, out)))
| Statement
On a planet far, far away, M languages are spoken. They are conveniently
numbered 1 through M.
For _CODE FESTIVAL 20XX_ held on this planet, N participants gathered from all
over the planet.
The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1},
L_{i,2}, ..., L_{i,{}K_i}.
Two participants A and B can _communicate_ with each other if and only if one
of the following conditions is satisfied:
* There exists a language that both A and B can speak.
* There exists a participant X that both A and B can communicate with.
Determine whether all N participants can communicate with all other
participants. | [{"input": "4 6\n 3 1 2 3\n 2 4 2\n 2 4 6\n 1 6", "output": "YES\n \n\nAny two participants can communicate with each other, as follows:\n\n * Participants 1 and 2: both can speak language 2.\n * Participants 2 and 3: both can speak language 4.\n * Participants 1 and 3: both can communicate with participant 2.\n * Participants 3 and 4: both can speak language 6.\n * Participants 2 and 4: both can communicate with participant 3.\n * Participants 1 and 4: both can communicate with participant 2.\n\nNote that there can be languages spoken by no participant.\n\n* * *"}, {"input": "4 4\n 2 1 2\n 2 1 2\n 1 3\n 2 4 3", "output": "NO\n \n\nFor example, participants 1 and 3 cannot communicate with each other."}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s987703689 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | print(360 / int(input()))
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s297400578 | Accepted | p02633 | Input is given from Standard Input in the following format:
X | x=int(input())
for i in range(1,x+1):
if 360*i%x==0:
print(360*i//x)
exit() | Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s324556134 | Accepted | p02633 | Input is given from Standard Input in the following format:
X | X = int(input())
ls = [2, 2, 2, 3, 3, 5]
a = []
for l in ls:
if X % l == 0:
a.append(l)
X /= l
num = 1
if len(a) != 0:
for b in a:
num *= b
print(int(360 / num))
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s388397556 | Accepted | p02633 | Input is given from Standard Input in the following format:
X | x = int(input())
if 360 % x == 0:
print(int(360 / x)) # 2 * 2 * 2 * 3 * 3 * 5
else:
count_2 = 0
count_3 = 0
count_5 = 0
while x % 2 == 0:
count_2 += 1
x /= 2
if count_2 == 3:
break
while x % 3 == 0:
count_3 += 1
x /= 3
if count_3 == 2:
break
while x % 5 == 0:
count_5 += 1
x /= 5
if count_5 == 1:
break
print((2 ** (3 - count_2)) * (3 ** (2 - count_3)) * (5 ** (1 - count_5)))
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s407521511 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | print(360 // (180 - int(input())))
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s024149456 | Accepted | p02633 | Input is given from Standard Input in the following format:
X | import math
turn_angle = int(input())
current_angle = 90
position_dict = {"x": 0, "y": 0}
move_one = {"x": 0, "y": 1}
num_actions = 1
def change_angle(turn_angle, current_angle):
current_angle = current_angle + turn_angle
if current_angle > 360:
current_angle = current_angle - 360
return current_angle
def resolve_direction(current_angle):
radian_angle = (current_angle * math.pi) / 180
move_dict = {
"x": round(math.cos(radian_angle), 3),
"y": round(math.sin(radian_angle), 3),
}
return move_dict
def move_skater(position_dict, move_dict):
for key, value in position_dict.items():
position_dict[key] = round((value + move_dict.get(key, 0)), 3)
return position_dict
position_dict = move_skater(position_dict, move_one)
current_angle = change_angle(turn_angle, current_angle)
origin_dict = {"x": 0.0, "y": 0.0}
while position_dict != origin_dict:
move_dict = resolve_direction(current_angle)
position_dict = move_skater(position_dict, move_dict)
current_angle = change_angle(turn_angle, current_angle)
num_actions = num_actions + 1
print(num_actions)
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s187430231 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | import math
delta=int(input())
theta=90+delta
dist= 1
x,y=0,1
count=1
while(round(dist)!=0):
rad= theta*math.pi/180
vx= math.cos(rad)
vy=math.sin(rad)
x+=vx
y+=vy
dist= math.sqrt(x*x+y*y)
count+=1
theta=(theta+delta)%360
print(count)
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s642541385 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | s = input()
s = int(s)
print(360 / s)
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s986731026 | Accepted | p02633 | Input is given from Standard Input in the following format:
X | # for i in range(m):
# for i in range(int(input())):
# n,k= map(int, input().split())
# for _ in range(int(input())):
# n,k= map(int, input().split())
# from collections import Counter
n = int(input())
if n % 360 == 0:
print(0)
exit()
else:
var = 1
while (var * n) % 360 != 0:
var += 1
print(var)
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s901800220 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | print(int(1 / (int(input()) / 360)))
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s313438260 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | 90
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Print the number of times Takahashi will do the action before he is at the
starting position again.
* * * | s158109982 | Wrong Answer | p02633 | Input is given from Standard Input in the following format:
X | k = int(input())
d, r = divmod(360, k)
while r:
x, y = divmod(360, r)
r = y
d += x
print(d)
| Statement
Takahashi is standing on a two-dimensional plane, facing north. Find the
minimum positive integer K such that Takahashi will be at the starting
position again after he does the following action K times:
* Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. | [{"input": "90", "output": "4\n \n\nTakahashi's path is a square.\n\n* * *"}, {"input": "1", "output": "360"}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.