848. 有向图的拓扑序列
作者:
闪回
,
2024-03-24 19:12:01
,
所有人可见
,
阅读 2
记录入度数
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int val[N],ne[N],h[N],idx;
queue<int> q;
vector<int> ans;
int degree[N];
int n,m;
void add(int a,int b)
{
val[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
bool topsort()
{
for(int i = 1;i<=n;i++)
{
if(degree[i] == 0)q.push(i);
}
while(q.size())
{
int t = q.front();
ans.push_back(t);
q.pop();
for(int i = h[t];~i;i = ne[i])
{
int j = val[i];
if(--degree[j] == 0)q.push(j);
}
}
return ans.size() == n;
}
int main()
{
cin>>n>>m;
memset(h, -1, sizeof h);
while(m--)
{
int a,b;
cin>>a>>b;
add(a,b);
degree[b]++;
}
if(topsort())
{
for(int i = 0;i<ans.size();i++)cout<<ans[i]<<" ";
}
else puts("-1");
return 0;
}