题解 | #【模板】拓扑排序#

【模板】拓扑排序

https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c

import sys
from collections import deque


class AdjacencyGraph:
    def __init__(self, n):
        # 有向图采用边的方式构成图,图有n个节点
        self.n = n
        self.graph = [[] for _ in range(n)]  # 生成一个包含 m 个空列表的列表。
        self.indegree = [0] * n

    def check_shape(self):
        print(self.graph)

    def add_edge(self, u, v):
        # 由于索引是[0,n-1]一共16个数,所以需要进行减一操作
        self.graph[u - 1].append(v - 1)
        self.indegree[v - 1] += 1

    def topological_sort(self):
        # Use deque for efficient pop from the left
        queue = deque([i for i in range(self.n) if self.indegree[i] == 0])
        topo_order = []

        while queue:
            node = queue.popleft()
            topo_order.append(node)

            for neighbor in self.graph[node]:
                self.indegree[neighbor] -= 1
                if self.indegree[neighbor] == 0:
                    queue.append(neighbor)

        # If topo_order does not contain all nodes, there is a cycle
        if len(topo_order) != self.n:
            return -1
        return topo_order


n,m = map(int,input().split())
Graph = AdjacencyGraph(n)
# Graph.check_shape()
for i in range(m):
    u, v = map(int,input().split())
    Graph.add_edge(u, v)

# Graph.check_shape()
res = Graph.topological_sort()
if res!=-1:
    res = [x + 1 for x in res]
    # print(len(res),res)
    print(" ".join(map(str, res)))
else:
    print(-1)

全部评论

相关推荐

野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
ResourceUtilization:差不多但是估计不够准确,一面没考虑到增长人口,另一方面也没考虑到能上大学的人数比例,不过我猜肯定只多不少
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务