結果

問題 No.2337 Equidistant
ユーザー gew1fw
提出日時 2025-06-12 19:43:20
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 2,363 bytes
コンパイル時間 228 ms
コンパイル使用メモリ 81,912 KB
実行使用メモリ 183,316 KB
最終ジャッジ日時 2025-06-12 19:43:43
合計ジャッジ時間 22,004 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 3 WA * 25
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

def main():
    sys.setrecursionlimit(1 << 25)
    input = sys.stdin.read
    data = input().split()
    idx = 0
    N = int(data[idx])
    idx += 1
    Q = int(data[idx])
    idx += 1

    edges = [[] for _ in range(N+1)]
    for _ in range(N-1):
        a = int(data[idx])
        idx += 1
        b = int(data[idx])
        idx += 1
        edges[a].append(b)
        edges[b].append(a)

    # Precompute distance from all nodes to all others is O(N^2), which is impossible for N=2e5.
    # Instead, for each query, compute distance between S and T using BFS.
    # But for 2e5 queries, each O(N), it's 4e10 operations, which is way too slow.
    # So, we need a better way: for each query, compute distance between S and T using BFS, but optimized.
    # Wait, perhaps we can compute distance using LCA with binary lifting.

    # So, first, compute parent, depth, and binary lifting table for LCA.

    # Compute parent and depth for each node using BFS
    parent = [0]*(N+1)
    depth = [0]*(N+1)
    visited = [False]*(N+1)
    q = deque()
    q.append(1)
    visited[1] = True
    while q:
        u = q.popleft()
        for v in edges[u]:
            if not visited[v]:
                visited[v] = True
                parent[v] = u
                depth[v] = depth[u] + 1
                q.append(v)

    # Now, compute binary lifting table for LCA
    LOG = 20
    up = [[0]*(N+1) for _ in range(LOG)]
    up[0] = parent
    for k in range(1, LOG):
        for v in range(1, N+1):
            up[k][v] = up[k-1][up[k-1][v]]

    def lca(u, v):
        if depth[u] < depth[v]:
            u, v = v, u
        # Bring u to the same depth as v
        for k in range(LOG-1, -1, -1):
            if depth[u] - (1 << k) >= depth[v]:
                u = up[k][u]
        if u == v:
            return u
        for k in range(LOG-1, -1, -1):
            if up[k][u] != up[k][v]:
                u = up[k][u]
                v = up[k][v]
        return parent[u]

    def distance(u, v):
        a = lca(u, v)
        return depth[u] + depth[v] - 2 * depth[a]

    for _ in range(Q):
        S = int(data[idx])
        idx +=1
        T = int(data[idx])
        idx +=1
        d = distance(S, T)
        if d % 2 == 0:
            print(1)
        else:
            print(0)

if __name__ == "__main__":
    main()
0