拓扑排序
作者:互联网
#include<cstdio> #include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; int n, m; void topo(vector<int>& rec, queue<int>&q) { for (int i = 1; i <= n; i++) if (rec[i] == 0) { q.push(i); rec[i] = -1; } } int main(void) { while (cin >> n >> m &&( n != 0 || m != 0)) { vector < vector<int>> oni(n+1); vector<int>rec(n+1), ans; rec.resize(n + 1); queue<int> toposort; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; rec[b]++; oni[a].push_back(b); } topo(rec, toposort); while (!toposort.empty()) { int t = toposort.front(); toposort.pop(); ans.push_back(t); for (int v : oni[t])rec[v]--; topo(rec, toposort); } for (int i = 0; i < ans.size(); i++) { printf("%d%s", ans[i], i == ans.size() - 1 ? "\n" : " "); } } }
标签:toposort,include,int,拓扑,oni,ans,rec,排序 来源: https://www.cnblogs.com/loliconsk/p/14425998.html