AcWing 846. 树的重心 python
原题链接
简单
作者:
申侠
,
2020-10-21 20:08:55
,
所有人可见
,
阅读 277
class graph(object):
def __init__(self,n,N=200010):
self.h = [-1] * N
self.e = [None] * N
self.ne = [None] * N
self.idx = 0
self.st = [False] * N
self.n = n
self.max_num_after_delete_gravity = 10e9
self.gravity_label = 1
def add(self, a, b):
self.e[self.idx] = b
self.ne[self.idx] = self.h[a]
self.h[a] = self.idx
self.idx += 1
def dfs(self, u):
# do something
self.st[u] = True
i = self.h[u]
while i != -1:
v = self.e[i] # childNode
if not self.st[v]:
self.dfs(v)
i = self.ne[i]
def find_gravity(self, u):
# do something
self.st[u] = True
i = self.h[u]
s = -10e9
t = 1
while i != -1:
v = self.e[i] # childNode
if not self.st[v]:
m = self.find_gravity(v)
s = max(s, m)
t += m
i = self.ne[i]
s = max(s, self.n-t)
# print(f'label:{u},idx:{self.n}, t:{t} , max_num:{s}')
if self.max_num_after_delete_gravity > s:
self.max_num_after_delete_gravity = s
self.gravity_label = u
return t
n = int(input())
g = graph(n)
for _ in range(n-1):
a, b = list(map(int, input().split(" ")))
g.add(a, b)
g.add(b, a)
g.find_gravity(1)
print(g.max_num_after_delete_gravity)