#include <iostream>
#include <vector>
#include <queue>
using namespace std;
constexpr int N = 1e3+5;
int n,m;
vector<int> edges[N];
vector<int> indegree(N,0);
vector<int> ans_sequence;
bool topo_sort() {
queue<int> q;
int cnt = 0;
for(int i = 1;i<=n;++i) {
if(indegree[i]==0) {
q.emplace(i);
cnt++;
}
}
while(!q.empty()) {
auto t = q.front();
q.pop();
ans_sequence.emplace_back(t);
for(int &i:edges[t]) {
if(--indegree[i]==0) {
cnt++;
q.emplace(i);
}
}
}
if(cnt<n) return false;
return true;
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> m;
while(m--) {
int x,y;
edges[x].emplace_back(y);
++indegree[y];
}
if(topo_sort()) {
for(int i = 0;i<ans_sequence.size();++i) {
cout << ans_sequence[i] << " \n"[i==ans_sequence.size()-1];
}
}else {
cout << "topo sort failed!\n";
}
return 0;
}
09-21
595
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-06
1445
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交