代码如下:
#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;
}
测试结果: