#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;typedef pair<int,int>PII;constint N=1e5+10;constint MOD=1e9+7;constint INF=0X3F3F3F3F;constint dx[]={-1,1,0,0,-1,-1,+1,+1};constint dy[]={0,0,-1,1,-1,+1,-1,+1};constint M =1e6+10;
vector<vector<int>>v(N);int d[N], q[N];int n, m;booltopsort(){int hh =0, tt =-1;for(int i =1; i <= n; i++){if(!d[i]) q[++tt]= i;}while(hh <= tt){int t = q[hh++];for(auto it : v[t]){
d[it]--;if(d[it]==0) q[++tt]= it;}}return tt == n -1;}intmain(){
cin >> n >> m;for(int i =0; i < m; i++){int a, b;
cin >> a >> b;
d[b]++;
v[a].push_back(b);}if(topsort()){for(int i =0; i < n; i++){
cout << q[i]<<" ";}
cout << endl;}else{
cout <<"-1"<< endl;}return0;}
模板二:
#include<bits/stdc++.h>usingnamespace std;constint N =100010;int n , m;int h[N], e[N], ne[N], idx;int q[N], d[N];voidadd(int a,int b){
e[idx]= b;//存值
ne[idx]= h[a];//索引指向头指针
h[a]= idx ++;//头指针向右移动}booltopsort(){int hh =0, tt =-1;//初始化for(int i =1; i <= n; i ++){if(!d[i]) q[++tt]= i;}while(hh <= tt){int 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;}intmain(){
cin >> n >> m;memset(h,-1,sizeof(h));for(int i =0; i < m; i ++){int a, b;
cin >> a >> b;add(a, b);
d[b]++;//a指向b,b有入度所以加一}if(topsort()){for(int i =0; i < n; i ++){
cout << q[i]<<" ";}
cout << endl;}else cout <<-1<< endl;return0;}