将入度为零的点加入队列,扫描入度为零的点的相邻点,将齐入度消减,如果出现入度为零的点将其加入队列,重复操作直到队列size为零
#include<iostream>
#include<cstring>
using namespace std;
const int N = 100010;
int n, m;
int h[N], e[N], ne[N], idx;//邻接表
int d[N];//入度
int q[N], hh, tt;//队列 hh 头指针 tt 尾指针
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx;
idx++;
}
int topsort()
{
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;
}
}
if (hh < n)return 0;//自环 不存在拓扑序
else return 1;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
d[b] ++;//b的入度加一
}
if (topsort())
for (int i = 0; i < n; i++)cout << q[i] << " ";
else cout << "-1 ";
return 0;
}