算法思路
数组模拟队列
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 100010;
int n, m;
int e[N], ne[N], h[N], idx;
int q[N];
int d[N]; //d[i]存储点i的入度
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
//判断是否有拓扑排序
bool topsort()
{
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];
if(--d[j] == 0)
q[++ tt] = j;
}
}
//如果所有点都入队了,说明存在拓扑序列;否则不存在拓扑序列。
return tt == n-1;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof(h));// 初始化
while(m--)
{
int x, y;
cin >> x >> y;
add(x, y);
d[y] ++; // y的入度+1
}
if(!topsort()) cout << "-1" <<endl;
else
{
for(int i = 0; i < n; i ++) cout << q[i] <<" ";
cout<<endl;
}
return 0;
}