結果
問題 | No.2337 Equidistant |
ユーザー |
![]() |
提出日時 | 2025-03-26 15:47:13 |
言語 | PyPy3 (7.3.15) |
結果 |
WA
|
実行時間 | - |
コード長 | 3,473 bytes |
コンパイル時間 | 280 ms |
コンパイル使用メモリ | 82,416 KB |
実行使用メモリ | 237,996 KB |
最終ジャッジ日時 | 2025-03-26 15:48:17 |
合計ジャッジ時間 | 38,848 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 1 WA * 26 TLE * 1 |
ソースコード
import sysfrom collections import dequedef main():input = sys.stdin.read().split()ptr = 0N, Q = int(input[ptr]), int(input[ptr+1])ptr +=2edges = [[] for _ in range(N+1)]for _ in range(N-1):a = int(input[ptr])b = int(input[ptr+1])edges[a].append(b)edges[b].append(a)ptr +=2LOG = 20parent = [[-1]*(LOG) for _ in range(N+1)]depth = [0]*(N+1)children = [[] for _ in range(N+1)]visited = [False]*(N+1)q = deque()q.append(1)visited[1] = Trueparent[1][0] = -1while q:u = q.popleft()for v in edges[u]:if not visited[v] and v != parent[u][0]:parent[v][0] = udepth[v] = depth[u] +1visited[v] = Truechildren[u].append(v)q.append(v)for k in range(1, LOG):for u in range(1, N+1):if parent[u][k-1] != -1:parent[u][k] = parent[parent[u][k-1]][k-1]else:parent[u][k] = -1size = [1]*(N+1)stack = [(1, False)]while stack:u, processed = stack.pop()if processed:for v in children[u]:size[u] += size[v]else:stack.append((u, True))for v in reversed(children[u]):stack.append((v, False))def lca(u, v):if depth[u] < depth[v]:u, v = v, ufor k in reversed(range(LOG)):if depth[u] - (1 << k) >= depth[v]:u = parent[u][k]if u == v:return ufor k in reversed(range(LOG)):if parent[u][k] != -1 and parent[u][k] != parent[v][k]:u = parent[u][k]v = parent[v][k]return parent[u][0]def get_kth_ancestor(u, k):current = ufor i in range(LOG):if (k >> i) & 1:if current == -1:return -1current = parent[current][i]if current == -1:return -1return currentoutput = []for _ in range(Q):S = int(input[ptr])T = int(input[ptr+1])ptr +=2L = lca(S, T)a = depth[S] - depth[L]b = depth[T] - depth[L]D = a + bif D % 2 != 0:output.append('0')continuek = D // 2if k <= a:M = get_kth_ancestor(S, k)else:required = b - (k - a)M = get_kth_ancestor(T, required)if M == -1:output.append('0')continuek1 = depth[S] - depth[M]if k1 == 0:u = Selse:u = get_kth_ancestor(S, k1 - 1)if u == -1:output.append('0')continuek2 = depth[T] - depth[M]if k2 == 0:v = Telse:v = get_kth_ancestor(T, k2 - 1)if v == -1:output.append('0')continueif parent[u][0] != M or parent[v][0] != M:output.append('0')continueanswer = size[M] - size[u] - size[v]output.append(str(answer))print('\n'.join(output))if __name__ == "__main__":main()