- 有向无环图的拓扑序列存在tp数组中,通过toposort函数给tp数组赋值。
- 判断一个有向图是否有环,就是判断这个有向图是否存在拓扑序列,若拓扑序列不存在,则有环。
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
vector<int> tp;
queue<int> q;
int din[N];
int h[N], e[N], ne[N], idx;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int n, m;
bool toposort()
{
for (int i = 1; i <= n; i ++ )
if (!din[i])
q.push(i);
while (q.size())
{
int f = q.front(); q.pop();
tp.push_back(f);
for (int i = h[f]; i != -1; i = ne[i])
{
int j = e[i];
if (!(-- din[j])) q.push(j);
}
}
return tp.size() == n;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i ++ )
{
int x, y;
cin >> x >> y;
add(x, y);
din[y] ++ ;
}
if (toposort())
{
for (int i = 0; i < tp.size(); i ++ )
cout << tp[i] << " ";
}
else cout << -1 << endl;
return 0;
}