AcWing 848. 有向图的拓扑序列
原题链接
简单
作者:
iiiih
,
2024-11-28 09:39:53
,
所有人可见
,
阅读 1
用c++STL queue的解法
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
const int N = 1e5 + 10;
int e[N], ne[N], h[N], idx, d[N];
int n, m;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool topsort()
{
vector<int>result;
//初始化队列
queue<int>q;
for (int i = 1; i <= n; i++)
if (d[i] == 0)
q.push(i);
while (!q.empty())
{
int t = q.front();
q.pop();
result.push_back(t);
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (--d[j] == 0)
{
q.push(j);
}
}
}
if (result.size() != n)return false;
for (auto x : result)
{
printf("%d ", x);
}
cout << endl;
return true;
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
d[b]++;
}
if (!topsort())cout << "-1" << endl;
return 0;
}