目录
观看教学视频写的代码。
一、846. 树的重心 - AcWing题库
N = int(1e5 + 5); M = N * 2
h = [-1] * N; e = [0] * M; ne = [0] * M
# h包含n个节点
idx = 0
st = [False for _ in range(N)]
def add(a, b):
# 添加一条a到b的有向线
global idx
# 新建一个节点
e[idx] = b
ne[idx] = h[a]
h[a] = idx
idx += 1
R = lambda: map(int, input().split())
n, = R()
for _ in range(n - 1):
a, b = R()
# 无向图转换为有向图
add(a, b)
add(b, a)
# 返回以该节点u为子树的节点值
def dfs(u):
global ans
sum = 1
res = 0 # 返回连通块节点数最大值
st[u] = True # 标记出发节点已经被搜过
i = h[u]
while i != -1: # 链表不为空,有连接节点
j = e[i]
if not st[j]:
s = dfs(j) # 遍历下一个节点
res = max(res, s) # 更新各连通块最大值
sum += s # 更新节点总数
i = ne[i] # 遍历下一个分支
res = max(res, n - sum) # 更新父图的连通块点数
ans = min(ans, res)
return sum
ans = N
dfs(1) # 从1开始
print(ans)
二、847. 图中点的层次 - AcWing题库
from collections import deque
N = int(1e5 + 5)
h = [-1] * N; e = [0] * N; ne = [0] * N # 尾节点为-1
path = [-1] * N
idx = 0
def add(a, b):
global idx
e[idx] = b
ne[idx] = h[a]
h[a] = idx
idx += 1
R = lambda: map(int, input().split())
n, m = R()
for _ in range(m):
a, b = R()
add(a, b)
def bfs():
q = deque([]) # 储存节点值
q.append(1) # 节点1
path[1] = 0
while q:
t = q.popleft()
i = h[t]
while i != -1:
# 节点存在
val = e[i] # 取节点值
if path[val] == -1:
# 未被遍历
path[val] = path[t] + 1
q.append(val)
i = ne[i]
return path[n]
print(bfs())
三、848. 有向图的拓扑序列 - AcWing题库
'''
将入度为0的点入队(入序)
最后所有点都入队了即为无环存在拓扑序
队列里面的次序即为拓扑序
'''
N = int(1e5 + 5)
h = [-1] * N; e = [0] * N; ne = [0] * N; idx = 0
d = [0] * N # 记录入度
q = [0] * N # 数组模拟队列
def add(a, b):
global idx
e[idx] = b
ne[idx] = h[a]
h[a] = idx
idx += 1
R = lambda: map(int, input().split())
n, m = R()
for _ in range(m):
a, b = R()
add(a, b)
d[b] += 1 # b入度加一
def topsort():
# 返回是否含有拓扑序,有则返回拓扑序
hh, tt = 0, -1
# 将入度为0的点入队
for i in range(1, n + 1):
if d[i] == 0:
tt += 1
q[tt] = i
while hh <= tt:
t = q[hh]
hh += 1
i = h[t]
while i != -1:
j = e[i]
d[j] -= 1
if d[j] == 0:
tt += 1
q[tt] = j
i = ne[i]
return tt == n - 1 # 是不是所有点都入队了
if topsort():
for i in range(n):
print(q[i], end = ' ')
else:
print(-1)
完
感谢你看到这里!一起加油吧!