拓扑排序
#include <bits/stdc++.h> using namespace std; const int maxn = 5e5 + 10; int N, M; int h[maxn], v[maxn], in[maxn], nx[maxn]; int sz = 0; void init() { for(int i = 1; i <= N; i ++) { h[i] = -1; in[i] = 0; } sz = 0; } void add(int a, int b) { v[sz] = b; nx[sz] = h[a]; h[a] = sz; in[b] ++; sz ++; } void TopSort() { queue<int> q; vector<int> ans; for(int i = 1; i <= N; i ++) { if(in[i] == 0) q.push(i); } while(!q.empty()) { int tp = q.front(); q.pop(); ans.push_back(tp); for(int i = h[tp]; i != -1; i = nx[i]) { in[v[i]] --; if(in[v[i]] == 0) q.push(v[i]); } } if(ans.size() != N) printf("NO\n"); else { for(int i = 0; i < ans.size(); i ++) printf("%d%s", ans[i], i != ans.size() - 1 ? " " : "\n"); } } int main() { while(~scanf("%d%d", &N, &M)) { init(); for(int i = 0; i < M; i ++) { int a, b; scanf("%d%d", &a, &b); add(a, b); } TopSort(); } return 0; }
see u again