結果
| 問題 |
No.2786 RMQ on Grid Path
|
| コンテスト | |
| ユーザー |
norioc
|
| 提出日時 | 2025-02-26 01:53:24 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 4,832 ms / 6,000 ms |
| コード長 | 2,518 bytes |
| コンパイル時間 | 302 ms |
| コンパイル使用メモリ | 82,020 KB |
| 実行使用メモリ | 353,876 KB |
| 最終ジャッジ日時 | 2025-02-26 01:55:06 |
| 合計ジャッジ時間 | 83,168 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 35 |
ソースコード
from collections.abc import Iterator
def neighbors4(r: int, c: int) -> Iterator[tuple[int, int]]:
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr = r + dr
nc = c + dc
if not (0 <= nr < H and 0 <= nc < W): continue
yield nr, nc
class UnionFind:
def __init__(self, n: int):
self.data = [-1] * (n+1)
self.nexts = [i for i in range(n+1)]
def root(self, a: int) -> int:
if self.data[a] < 0: return a
self.data[a] = self.root(self.data[a])
return self.data[a]
def unite(self, a: int, b: int) -> bool:
pa = self.root(a)
pb = self.root(b)
if pa == pb: return False
if self.data[pa] > self.data[pb]:
pa, pb = pb, pa
self.data[pa] += self.data[pb] # pa を pb をつなげる
self.data[pb] = pa
self.nexts[pa], self.nexts[pb] = self.nexts[pb], self.nexts[pa]
return True
def issame(self, a: int, b: int) -> bool:
return self.root(a) == self.root(b)
def size(self, a: int) -> int:
"""a が属する集合のサイズ"""
return -self.data[self.root(a)]
def group(self, a: int):
"""a が属する集合"""
yield a
x = a
while self.nexts[x] != a:
x = self.nexts[x]
yield x
INF = 1 << 60
H, W = map(int, input().split())
G = []
ub = 0
for _ in range(H):
G.append(list(map(int, input().split())))
ub = max(ub, max(G[-1]))
Q = int(input())
queries = []
for i in range(Q):
sr, sc, tr, tc = map(lambda x: int(x)-1, input().split())
s = sr * W + sc
t = tr * W + tc
queries.append((s, t, i))
conn_map = [[] for _ in range(ub+1)]
for i in range(H):
for j in range(W):
for nr, nc in neighbors4(i, j):
h = max(G[i][j], G[nr][nc])
s = i * W + j
t = nr * W + nc
if s < t:
conn_map[h].append((s, t))
lefts = [1] * Q
rights = [ub] * Q
for _ in range(18):
h2i = [[] for _ in range(ub+1)]
for i, (a, b) in enumerate(zip(lefts, rights)):
m = (a + b) // 2
h2i[m].append(i)
uf = UnionFind(H * W + 10)
for h in range(1, ub+1):
for s, t in conn_map[h]:
uf.unite(s, t)
for qi in h2i[h]:
s = queries[qi][0]
t = queries[qi][1]
if uf.issame(s, t):
rights[qi] = h
else:
lefts[qi] = h
for qi in range(Q):
ans = rights[qi]
print(ans)
norioc