結果
問題 | No.2337 Equidistant |
ユーザー |
|
提出日時 | 2023-06-02 22:36:07 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 2,512 ms / 4,000 ms |
コード長 | 3,018 bytes |
コンパイル時間 | 745 ms |
コンパイル使用メモリ | 82,176 KB |
実行使用メモリ | 173,204 KB |
最終ジャッジ日時 | 2024-12-28 20:18:39 |
合計ジャッジ時間 | 40,075 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 28 |
ソースコード
## library of LCA by class## index start from 0import syssys.setrecursionlimit(10**5+5)from collections import dequeclass LCA:def __init__(self,n):self.size = nself.bitlen = n.bit_length()self.ancestor = [[0]*self.size for i in range(self.bitlen)]self.depth = [-1]*self.sizeself.dis = [-1]*self.size## using [log_n][n] [n][log_n]## [log_n][n] is tend to faster than [n][log_n]## get parent by bfs is probably faster than dfsdef make(self,root):self.depth[root] = 0self.dis[root] = 0q = deque([root])while q:now = q.popleft()for nex in e[now]:if self.depth[nex]>= 0:continueself.depth[nex] = self.depth[now]+1self.dis[nex] = self.dis[now]+1self.ancestor[0][nex] = nowq.append(nex)for i in range(1,self.bitlen):for j in range(self.size):if self.ancestor[i-1][j] > 0:self.ancestor[i][j] = self.ancestor[i-1][self.ancestor[i-1][j]]def lca(self,x,y):dx = self.depth[x]dy = self.depth[y]if dx < dy:x,y = y,xdx,dy = dy,dxdif = dx-dywhile dif:s = dif & (-dif)x = self.ancestor[s.bit_length()-1][x]dif -= swhile x != y:j = 0while self.ancestor[j][x] != self.ancestor[j][y]:j += 1if j == 0:return self.ancestor[0][x]x = self.ancestor[j-1][x]y = self.ancestor[j-1][y]return xdef par(self,x,dep):now = xfor i in range(self.bitlen)[::-1]:if 1 << i <= dep:now = self.ancestor[i][now]dep -= 1<<ireturn nown,Q = map(int,input().split())e = [[] for i in range(n)]for i in range(n-1):a,b= map(int,input().split())a -= 1b -= 1e[a].append(b)e[b].append(a)childs = [0]*nvis = [0]*nq = [0]vis[0] = 1topo = []par = [-1]*nwhile q:now = q.pop()topo.append(now)for nex in e[now]:if vis[nex]:continuepar[nex] = nowvis[nex] = 1q.append(nex)for now in topo[::-1]:count = 1for nex in e[now]:if nex == par[now]:continuecount += childs[nex]childs[now] = countlca = LCA(n)lca.make(0)for _ in range(Q):s,t = [int(x)-1 for x in input().split()]if lca.depth[s] < lca.depth[t]:s,t = t,sp = lca.lca(s,t)dis = lca.depth[s]+lca.depth[t] - lca.depth[p]*2if dis%2:print(0)continuecenter = lca.par(s,dis//2)if lca.depth[s] == lca.depth[t]:ans = n - childs[lca.par(s,dis//2-1)] - childs[lca.par(t,dis//2-1)]else:ans = childs[center]ans -= childs[lca.par(s,dis//2-1)]print(ans)