結果

問題 No.3309 Aging Railway
コンテスト
ユーザー norioc
提出日時 2025-11-05 00:35:38
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,414 ms / 3,000 ms
コード長 1,771 bytes
コンパイル時間 260 ms
コンパイル使用メモリ 82,320 KB
実行使用メモリ 191,896 KB
最終ジャッジ日時 2025-11-05 00:35:58
合計ジャッジ時間 19,863 ms
ジャッジサーバーID
(参考情報)
judge7 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n: int):
        self.data = [-1] * (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
        return True

    def is_same(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 copy(self):
        res = UnionFind(0)
        res.data = self.data.copy()
        return res

def bsearch_right(low: int, high: int, pred) -> int:
    assert pred(high)
    lo = low
    hi = high
    res = high
    while lo <= hi:
        m = (lo + hi) // 2
        if pred(m):
            res = min(res, m)
            hi = m - 1
        else:
            lo = m + 1

    return res


from itertools import accumulate

N, M = map(int, input().split())
edges = []
for _ in range(N-1):
    u, v = map(lambda x: int(x)-1, input().split())
    edges.append((u, v))

xs = []
for _ in range(M):
    s, t = map(lambda x: int(x)-1, input().split())
    xs.append((s, t))

ufs = [UnionFind(N)]
# 線路の廃線を逆からみる
for u, v in reversed(edges):
    cur = ufs[-1].copy()
    cur.unite(u, v)
    ufs.append(cur)

ps = [0] * N
for s, t in xs:
    p = bsearch_right(0, len(ufs)-1, lambda m: ufs[m].is_same(s, t))
    ps[p] += 1

ps.pop()
acc = list(accumulate(ps))
print(*reversed(acc), sep='\n')
0