题目描述
输入样例
3 3
1 2
2 3
1 3
输出样例
···
1 2 3
···
参考代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, m;
int e[N], ne[N], h[N], idx;
int d[N], q[N]; // d[N]存储每个节点的入度,q[N]存储入度为0的节点
void add(int a, int b)
{
e[idx] = b; ne[idx] = h[a]; h[a] = idx; idx++;
}
// 一个有向图,如果图中有入度为 0 的点,就把这个点删掉,同时也删掉这个点所连的边。
// 一直进行上面出处理,如果所有点都能被删掉,则这个图可以进行拓扑排序。
bool topsort()
{
int hh = 0, tt = -1;
for (int i = 1; i <= n; i++) // 点的编号是1~n,所以遍历寻找入度为0的点入队
if (!d[i])
q[++tt] = i;
while (hh <= tt) // 当队列不为空时,循环出队度为0的节点,并扩展新的节点
{
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;
}
int main()
{
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
while (m -- )
{
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
d[b]++;
}
if (topsort())
{
for (int i = 0; i < n; i++) printf("%d ", q[i]);
puts("");
}
else puts("-1");
return 0;
}