AcWing 846. 树的重心-python
原题链接
简单
作者:
Actor丶
,
2020-02-13 21:45:23
,
所有人可见
,
阅读 1585
"""
基本思想:
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 # !!!出错:这里要声明res为全局变量
st[u] = True
# print(u, res)
size = 0 # 用来存储以u为根的所有子树的节点的最大值(不包含u节点(根节点本身))
sumNode = 0 # 存储以u为根节点的所有子节点数(不包含u节点(根节点本身))
for i in graph[u]:
if not st[i]:
s = dfs(i) # 返回u节点的以i为根节点的子树的节点数
sumNode += s
size = max(size,s)
size = max(size, n-sumNode-1) # 减1:表示减去u节点本身
res = min(res, size)
return sumNode+1 # 加1:表示包含i节点的总节点数
# 1. 输入示例(n个节点的无向图)
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)
# 2. 初始化状态数组
st = [False for i in range(n+1)]
res = n
dfs(3)
print(res)
%%%