代码如下:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int N = 10010;
int in[N];
vector<int>v[N];
vector<int>print;//存放拓扑序列
int main()
{int n, m;//n为点的个数,m为边的条数,点的序号从0开始while (cin >> n >> m, n, m){memset(in, 0, sizeof(in));//清空入度for (int i = 0; i < n; i++) v[i].clear();for (int i = 1; i <= m; i++){int x, y;cin >> x >> y;v[x].push_back(y);//x指向yin[y]++;//y的入度+1}priority_queue<int, vector<int>, greater<int>>q;//优先队列,设置从小到大排序,小的在队列前面for (int i = 0; i < n; i++)if (!in[i]) q.push(i);//把入度为0的节点压入队列while (!q.empty()){int xx = q.top();print.push_back(xx);//也可以直接输出,不用存进这个vector容器也行q.pop();n--;//每次去掉一个节点for (int i = 0; i < v[xx].size(); i++){int yy = v[xx][i];in[yy]--;if (!in[yy])q.push(yy);//如果去掉上一个节点之后下一个节点的入度为0,则压入队列}}if (!n){for (vector<int>::iterator it = print.begin(); it != print.end(); it++){cout << *it << " ";}cout << endl;}elsecout << "No" << endl;//如果有环的话节点数不会为0}return 0;
}
测试结果: