题解 | 【模板】拓扑排序
【模板】拓扑排序
https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
import sys n, m = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(m)] # 整体思路: # 找到没有输入的点,将其加入拓扑序中,在图中删除该点,更新图,如此循环 # 直到所有的点都输出完毕,如果找不到没有输入的点,说明有环,输出-1 # 生成point_dict,键代表点,值为list,放置输入该点的点 """ for edge in a: 若point_dict中的键不含edge[0],那么point_dict加入一个键,并将值令为[] 如果point_dict的键不含edge[1],那么point_dict加入一个键,将值令为[edge[0]] 否则,对应键值加入edge[0] """ point_dict = {} for edge in a: if edge[0] not in point_dict.keys(): point_dict[edge[0]] = set() if edge[1] not in point_dict.keys(): point_dict[edge[1]] = {edge[0]} else: point_dict[edge[1]].add(edge[0]) # 当point_dict不为空时,进入循环 # 遍历每一个点,将没有输入的点加入cur_de。如果全部都有输入,输出-1,终止程序 # 要把没有输入的点在point_dict中去除 # 遍历point_dict.value(),去除list中上一步记录的点。 # 输出deque deque = [] while point_dict: cur = set() for point, pl in point_dict.items(): if not pl: # pl为空,即没有输入 cur.add(point) if not cur: # cur为空,即全部点都有输入 print(-1) sys.exit() for ele in cur: del point_dict[ele] for point, pl in point_dict.items(): if cur & pl: # cur_de和pl有交集 point_dict[point] = pl - cur deque.extend(list(cur)) print(" ".join(list(map(str, deque))))