解题思路:首先遍历一遍图,找出入度为0的点,把它push到队列中去,然后把这个点延伸出来的边都去除掉,(du[指向的点]–),最后判断是否还有入度不为0的点即可,如果还有的话,输出-1;
练习题
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
int in[N], h[N], ne[N], v[N], idx;
queue<int> q;
vector<int> ans;
void add(int a, int b){
ne[idx] = h[a], v[idx] = b, h[a] = idx++;
}
void topo(){
while(q.size()){
int now = q.front();
q.pop();
ans.push_back(now);
for(int i = h[now]; ~i; i = ne[i]){
int j = v[i];
in[j]--;
if(in[j] == 0) q.push(j);
}
}
}
int main(){
memset(h, -1, sizeof h);
int n, m;
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++){
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
in[b]++;
}
for(int i = 1; i <= n; i++){
if(in[i] == 0) q.push(i);
}
topo();
if(ans.size() != n) puts("-1");
else for(int k : ans) printf("%d ", k);
return 0;
}