C++实现拓扑排序(vector模拟邻接表存储,栈实现)
生活随笔
收集整理的這篇文章主要介紹了
C++实现拓扑排序(vector模拟邻接表存储,栈实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下:
#include<iostream> #include <vector> #include <string> #include <stack> using namespace std; const int N = 10010;int in[N]; vector<int>v[N]; vector<int>printElem;int main() {int n, m;while (cin >> n >> m, n, m){memset(in, 0, sizeof(in));for (int i = 0; i < n; i++) v[i].clear();for (int i = 0; i < m; i++){int x, y;cin >> x >> y;v[x].push_back(y);in[y]++;}stack<int>s;for (int i = 0; i < n; i++){if (!in[i])s.push(i);}while (!s.empty()){int xx = s.top();printElem.push_back(xx);//也可以直接輸出,不用存進這個vector容器也行n--;s.pop();for (int i = 0; i < v[xx].size(); i++){int yy = v[xx][i];in[yy]--;if (!in[yy]){s.push(yy);}}}if (!n){for (const auto &item : printElem) cout << item << " ";cout << endl;}else cout << "no" << endl;}return 0; }測試結果:
總結
以上是生活随笔為你收集整理的C++实现拓扑排序(vector模拟邻接表存储,栈实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 红薯粉条的功效与作用、禁忌和食用方法
- 下一篇: C++实现拓扑排序(邻接表存储,栈实现)