結果
| 問題 |
No.2337 Equidistant
|
| コンテスト | |
| ユーザー |
titia
|
| 提出日時 | 2023-10-03 04:37:29 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,729 bytes |
| コンパイル時間 | 256 ms |
| コンパイル使用メモリ | 82,376 KB |
| 実行使用メモリ | 205,324 KB |
| 最終ジャッジ日時 | 2024-07-26 13:58:19 |
| 合計ジャッジ時間 | 28,109 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 4 WA * 24 |
ソースコード
import sys
input = sys.stdin.readline
N,Q=map(int,input().split())
E=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
a-=1
b-=1
E[a].append(b)
E[b].append(a)
ROOT=0
QUE=[ROOT]
DEPTH=[0]*N
DEPTH[ROOT]=0
Parent=[-1]*N
Parent[ROOT]=N # ROOTの親を定めておく.
Child=[[] for i in range(N)]
TOP_SORT=[] # トポロジカルソート
while QUE: # トポロジカルソートと同時に親を見つける
x=QUE.pop()
TOP_SORT.append(x)
for to in E[x]:
if Parent[to]==-1:
Parent[to]=x
Child[x].append(to)
QUE.append(to)
DEPTH[to]=DEPTH[x]+1
Children=[1]*N
for x in TOP_SORT[::-1]: #(自分を含む)子ノードの数を調べる
if x==ROOT:
break
Children[Parent[x]]+=Children[x]
DOUBLING=[[-1]*N for b in range(30)]
for i in range(N):
if i!=ROOT:
DOUBLING[0][i]=Parent[i]
for b in range(1,30):
for i in range(N):
if DOUBLING[b-1][i]!=-1:
DOUBLING[b][i]=DOUBLING[b-1][DOUBLING[b-1][i]]
# 頂点aの先祖で深さdの頂点を探す
def search_depth(a,d):
now=a
for b in range(30,-1,-1):
if (DEPTH[a]-d) & (1<<b) != 0:
now=DOUBLING[b][now]
return now
def lca(x,y):
if DEPTH[x]<DEPTH[y]:
y=search_depth(y,DEPTH[x])
elif DEPTH[x]>DEPTH[y]:
x=search_depth(x,DEPTH[y])
if x==y:
return x
for b in range(29,-1,-1):
if DOUBLING[b][x]!=DOUBLING[b][y]:
x=DOUBLING[b][x]
y=DOUBLING[b][y]
if Parent[x]==Parent[y]:
return Parent[x]
for tests in range(Q):
a,b=map(int,input().split())
a-=1
b-=1
if DEPTH[a]>DEPTH[b]:
a,b=b,a
LCA=lca(a,b)
if LCA==a:
dis=DEPTH[b]-DEPTH[a]
if dis%2==1:
print(0)
continue
else:
x=search_depth(b,DEPTH[b]-dis//2)
y=search_depth(b,DEPTH[b]-dis//2+1)
print(Children[x]-Children[y])
else:
dis1=DEPTH[a]-DEPTH[LCA]
dis2=DEPTH[b]-DEPTH[LCA]
if (dis1+dis2)%2==1:
print(0)
continue
else:
if dis1==dis2:
print(N-Children[LCA]+1)
elif dis1>dis2:
x=search_depth(a,DEPTH[a]-(dis1+dis2)//2)
y=search_depth(a,DEPTH[a]-(dis1+dis2)//2+1)
print(Children[x]-Children[y])
else:
x=search_depth(b,DEPTH[b]-(dis1+dis2)//2)
y=search_depth(b,DEPTH[b]-(dis1+dis2)//2+1)
print(Children[x]-Children[y])
titia