AcWing 848. 有向图的拓扑序列
原题链接
简单
作者:
coordinate
,
2020-01-29 15:48:16
,
所有人可见
,
阅读 572
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010, M = 100010;
int n, m;
int h[N], e[M], ne[M], idx;
int d[N], seq[N]; //d:当前点入度
queue<int> q;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool topsort()
{
int cnt = 0;
// d[i] 存储点i的入度
for (int i = 1; i <= n; i ++ )
if (!d[i]) q.push(i);
while (!q.empty())
{
int t = q.front(); q.pop();
seq[cnt++] = t;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (--d[j] == 0)
q.push(j);
}
}
return cnt == n;
}
int main()
{
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]++;
}
if (topsort())
for (int i = 0;i < n; i++) cout << seq[i] << " " ;
else cout << -1;
}