# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
626033 | 54skyxenon | Mecho (IOI09_mecho) | Cpython 3 | 1095 ms | 25668 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
# https://oj.uz/problem/view/IOI09_mecho
from collections import deque
from math import ceil
n, s = map(int, input().split())
forest = []
for _ in range(n):
forest.append(input())
start = None
end = None
hives = []
for i in range(n):
for j in range(n):
if forest[i][j] == 'M':
start = (i, j)
if forest[i][j] == 'D':
end = (i, j)
if forest[i][j] == 'H':
hives.append((i, j))
def bs(lo, hi):
def ok(mid):
dist_hive = [[float('inf')] * n for _ in range(n)]
dist_mecho = [[float('inf')] * n for _ in range(n)]
dist_mecho[start[0]][start[1]] = mid
hives_Q = deque()
for i, j in hives:
dist_hive[i][j] = 0
hives_Q.append((i, j, 0))
while hives_Q:
r, c, depth = hives_Q.popleft()
for nr, nc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if 0 <= nr < n and 0 <= nc < n and forest[nr][nc] == 'G' and dist_hive[nr][nc] == float('inf'):
hives_Q.append((nr, nc, depth + 1))
dist_hive[nr][nc] = depth + 1
mecho_Q = deque([(start[0], start[1], 0)])
while mecho_Q:
r, c, depth = mecho_Q.popleft()
for nr, nc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if 0 <= nr < n and 0 <= nc < n and forest[nr][nc] == 'G' and dist_mecho[nr][nc] == float('inf'):
mecho_Q.append((nr, nc, depth + 1))
dist_mecho[nr][nc] = mid + ceil((depth + 1) / s)
# print('at mid =', mid)
# print('dist_hive:')
# print(*dist_hive, sep='\n')
# print('dist_mecho:')
# print(*dist_mecho, sep='\n')
r, c = end
for nr, nc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if 0 <= nr < n and 0 <= nc < n and forest[nr][nc] == 'G' and dist_mecho[nr][nc] < dist_hive[nr][nc]:
# print('mid =', mid, 'is good!')
return True
# print('mid =', mid, 'is bad!')
return False
if lo > hi:
return -1
mid = (lo + hi) // 2
if not ok(mid):
return bs(lo, mid - 1)
elif mid < hi and ok(mid + 1):
return bs(mid + 1, hi)
else:
return mid
print(bs(0, n ** 2))
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |