結果
| 問題 |
No.2337 Equidistant
|
| コンテスト | |
| ユーザー |
ニックネーム
|
| 提出日時 | 2023-06-02 22:19:53 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 2,287 ms / 4,000 ms |
| コード長 | 1,836 bytes |
| コンパイル時間 | 867 ms |
| コンパイル使用メモリ | 82,176 KB |
| 実行使用メモリ | 147,072 KB |
| 最終ジャッジ日時 | 2024-12-28 19:10:26 |
| 合計ジャッジ時間 | 33,648 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 28 |
ソースコード
class DoublingLCA:
def __init__(self,n,adj,root=0):
self.ancestor,self.depth = [[-1]*(n+1)],[-1]*n
stack = [(root,-1,0)]
while stack:
v,p,dep = stack.pop()
self.ancestor[0][v],self.depth[v] = p,dep
for c in adj[v]:
if c!=p: stack.append((c,v,dep+1))
for _ in range(max(self.depth).bit_length()-1):
self.ancestor.append([self.ancestor[-1][v] for v in self.ancestor[-1]])
def get_kth_ancestor(self,v,k):
for i in range(k.bit_length()):
if k>>i&1: v = self.ancestor[i][v]
return v
def get_lca(self,u,v):
depu,depv = self.depth[u],self.depth[v]
if depu>depv: u,v,depu,depv = v,u,depv,depu
v = self.get_kth_ancestor(v,depv-depu)
if u==v: return u
for k in range(depu.bit_length()-1,-1,-1):
nu,nv = self.ancestor[k][u],self.ancestor[k][v]
if nu!=nv: u,v = nu,nv
return self.ancestor[0][u]
from collections import deque
n,q = map(int,input().split())
adj = [[] for _ in range(n)]
for _ in range(n-1):
a,b = map(int,input().split())
adj[a-1].append(b-1); adj[b-1].append(a-1)
lca = DoublingLCA(n,adj)
dq = deque([0]); topo = []; par = [-1]*n
while dq:
p = dq.popleft(); topo.append(p)
for c in adj[p]:
if c!=par[p]: dq.append(c); par[c] = p
dp = [1]*n
for v in topo[::-1]:
for c in adj[v]:
if c!=par[v]: dp[v] += dp[c]
for _ in range(q):
s,t = map(int,input().split()); s -= 1; t -= 1
x = lca.depth[s]; y = lca.depth[t]
if x<y: s,t,x,y = t,s,y,x
d = x+y-2*lca.depth[lca.get_lca(s,t)]
a = lca.get_kth_ancestor(s,d//2)
b = lca.get_kth_ancestor(s,d//2-1)
c = lca.get_kth_ancestor(t,d//2-1)
if d%2: print(0)
elif x!=y: print(dp[a]-dp[b])
else: print(n-dp[b]-dp[c])
ニックネーム