http://tjuacm.chaosheng.top/problem.php?id=1272
https://vjudge.net/problem/HDU-1285
参考 https://blog.csdn.net/red_red_red/article/details/84329559
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int N = 510; int n, m; int vis[N]; int indegree[N]; int map[N][N]; void tuopu(){ // 维护入度为0的节点,编号从小到大排序,保证编号小的节点的拓扑序小 priority_queue<int,vector<int>,greater<int> >q;//优先级队列 for(int i = 1; i <= n; i++){ if(indegree[i] == 0){ q.push(i); } } bool temp = false;//控制空格 while(q.size()){ int top = q.top(); q.pop(); indegree[top]--; //已经输出的数,入度置为-1 if(!temp) printf("%d",top); else printf(" %d",top); temp = true; for(int i = 1; i <= n; i++){ if(map[top][i]){//与刚才输出的数,有关系的,入度-- indegree[i]--; if(!indegree[i]){ q.push(i); //如果成了0;进队 } } } } printf("\n"); } int main(){ int a, b; while(cin >> n >> m){ int f = 1; memset(map, 0, sizeof(map)); memset(indegree, 0, sizeof(indegree)); for(int i = 1; i <= m; i++){ cin >> a >> b; if(map[a][b] == 0){ map[a][b] = 1; indegree[b]++; } } tuopu(); } return 0; }