记住了l,r
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5+10; struct edge{ int to, nxt; }e[maxn]; int head[maxn], cnt; int n, m, x, y, q[maxn], r = -1, d[maxn], l; void add(int u, int v) { e[++cnt].to = v; e[cnt].nxt = head[u]; head[u] = cnt; } int topsort() { for(int i = 1; i <= n; i++) if(!d[i]) q[++r] = i; while(l <= r) { int now = q[l++]; for(int i = head[now]; i; i = e[i].nxt) { if(--d[e[i].to] == 0) q[++r] = e[i].to; } } if(r == n-1) return 1; else return 0; } int main() { cin >> n >> m; for(int i = 1; i <= m; i++) { cin >> x >> y; add(x, y); d[y]++; } if(topsort()) { for(int i = 0; i < n; i++) cout << q[i] << " " ; } else cout << "-1"; return 0; }
原文:https://www.cnblogs.com/lovezxy520/p/11845879.html