拓扑排序 -2025/11/22
拓扑排序
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int e[N], ne[N], h[N], idx;
int n, m, d[N];
int q[N];
void add(int a,int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
bool top_sort(){
int hh = 0, tt = -1;
for(int i = 1;i <= n; i++) {
if(d[i] == 0) q[++ tt] = i;
}
while(hh <= tt){
auto t = q[hh ++];
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
d[j] --;
if(d[j] == 0) q[++ tt] = j;
}
}
return tt == n - 1;
}
int main(){
// 单链表, h初始化为-1, 用于存储图时, 对于每一个头节点都要初始化为-1, 要不然会超时
memset(h, -1 , sizeof h);
cin >> n >> m;
for(int i = 1; i <= m; i++){
int a,b;
cin >> a >> b;
add(a , b);
d[b] ++;
}
if(top_sort()){
for(int i = 0;i < n; i++) cout << q[i] << " ";
}
else cout << "-1" << "\n";
return 0;
}

浙公网安备 33010602011771号