AcWing 846. 树的重心-python
原题链接
简单
作者:
Actor丶
,
2020-02-13 21:45:23
,
所有人可见
,
阅读 1609
"""
基本思想:
1. 图的存储模板:
graph = {}
n = int(input().strip())
for i in range(n-1):
a, b = map(int, input().split())
if a not in graph:
graph[a] = [b]
else:
graph[a].append(b)
### 存储无向图
if b not in graph:
graph[b] = [a]
else:
graph[b].append(a)
# 初始化状态数组
st = [False for i in range(n+1)]
2. 图的深度优先搜索模板:
def dfs(u):
st[u] = True
for i in range(graph[u]):
if not st[i]:
dfs(i)
"""
def dfs(u):
global res
st[u] = True
size = 0
sumNode = 0
for i in graph[u]:
if not st[i]:
s = dfs(i)
sumNode += s
size = max(size,s)
size = max(size, n-sumNode-1)
res = min(res, size)
return sumNode+1
graph = {}
n = int(input().strip())
for i in range(n-1):
a, b = map(int, input().split())
if a not in graph:
graph[a] = [b]
else:
graph[a].append(b)
if b not in graph:
graph[b] = [a]
else:
graph[b].append(a)
st = [False for i in range(n+1)]
res = n
dfs(3)
print(res)
%%%