拓扑排序的板子题。
思路
拓扑排序不懂的看oi-wiki。
先读入并记录每个点的入度,入度为 就扔到一个优先队列里。由于 priority_queue 默认降序,所以你可以使用 priority_queue<int,vector<int>,greater<int>> 或将节点编号取反再扔到队列里。这里我是节点编号取反后再扔队列里。
做一遍拓扑排序,由于使用了优先队列,所以能保证每次的节点编号都最小。这个过程中出队的节点记录在一个普通队列 ans 里(用数组或者别的什么也行),最后如果 ans 中元素数量小于 就说明有环,输出 IMPOSSIBLE,否则按顺序输出 ans 中的元素。
为什么这样就能判环呢?因为由于环的存在,环上节点入度始终不会为 ,不会进入队列,所以最后若有元素没有进过队列就说明有环。
本代码用链式前向星存图,不懂的见 oi-wiki。
代码
#include<cstdio>
#include<queue>
int head[100001],in[100001],to[200001],next[200001],cnt;
inline void add(const int& a,const int& b)
{
to[++cnt]=b;
next[cnt]=head[a];
head[a]=cnt;
in[b]++;
}//链式前向星存图
std::priority_queue<int>q;
std::queue<int>ans;//存答案
int main()
{
int n,m;
scanf("%d%d",&n,&m);
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
for(int i=1;i<=n;i++)
{
if(in[i]==0)q.push(-i);//入度为 0,入队
}
while(!q.empty())
{
int now=-q.top();//取反回来
q.pop();
ans.push(now);
for(int i=head[now];i;i=next[i])//遍历边
{
in[to[i]]--;
if(in[to[i]]==0)q.push(-to[i]);
}
}
if(ans.size()<n)//判环
{
puts("IMPOSSIBLE");
return 0;
}
while(!ans.empty())printf("%d ",ans.front()),ans.pop();//输出
return 0;
}