AcWing 217. 绿豆蛙的归宿 拓扑排序构造递推序列
原题链接
简单
作者:
皓首不倦
,
2020-09-17 16:36:39
,
所有人可见
,
阅读 566
import sys
from typing import List
from collections import deque
from collections import Counter
class TopoSort:
# edges是边列表, (a, b)代表一条边,表示a依赖于b, 返回拓扑排序之后的节点列表, 无法完成拓扑排序返回None
# 节点编号是1, 2, 3, .... node_num
@staticmethod
def sort(edges: List, node_num):
dep_cnt = [0] * (node_num + 1) # 每一个节点的依赖计数
link = {}
for a, b in edges:
if b not in link:
link[b] = []
link[b].append(a) # link[b]记录哪些点依赖b
dep_cnt[a] += 1
ans = []
valid_node = deque() # 当前入度为0的所有节点
for idx, degree in enumerate(dep_cnt[1:]):
if degree == 0:
valid_node.append(idx+1)
while len(ans) < node_num:
if len(valid_node) == 0:
return None
cur_node = valid_node.popleft()
if cur_node in link:
for next in link[cur_node]:
dep_cnt[next] -= 1
if dep_cnt[next] == 0:
valid_node.append(next)
ans.append(cur_node)
return ans
N, M = map(int, input().split())
edges = []
link = {i:[] for i in range(1, N+1)}
for _ in range(M):
a, b, w = map(int, input().split())
edges.append((a, b))
link[a].append((b, w))
ans = [0] * (N+1) # ans[i] 表示从i点走到终点的期望开销
sort_list = TopoSort.sort(edges, N)
for node in sort_list:
k = len(link[node])
for next_node, edge_len in link[node]:
ans[node] += (ans[next_node] + edge_len) / k
print('{:.2f}'.format(ans[1]))