#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int M =2500;
vector<int> g[M];
int in[M],n,m;
void Topo()
{
int path[M],k=0,sum=0;
priority_queue <int,vector<int>, greater<int> > q; // 排名不唯一 编号小的在前
while(1)
{
for(int i=1;i<=n;i++)
{
if(!in[i])
{
q.push(i);
break;// 排名不唯一 编号小的在前
}
}
sum+=q.size();
while(!q.empty())
{
int a=q.top();
path[k++]=a; //保存排名
in[a]--;// 标记访问
q.pop();
for(int i=0;i<g[a].size();i++)
{
in[g[a][i]]--;
}
}
if(sum==n) break;
}
for(int i=0;i<n;i++)
{
if(i!=n-1)
{
printf("%d ",path[i]);
}
else
printf("%d\n",path[i]);
}
}
int main()
{
while(cin>>n>>m)
{
memset(g,0,sizeof(g));
memset(in,0,sizeof(in));
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
g[a].push_back(b); // a->b
in[b]++;
}
Topo();
}
return 0;
}
hdu 1285 拓扑排序裸题
最新推荐文章于 2022-10-03 21:07:14 发布
本文介绍了一种使用优先队列实现图的拓扑排序的方法。通过不断寻找入度为0的节点并将其从图中移除的方式,最终获得一个符合拓扑排序规则的节点序列。适用于解决依赖关系排序等问题。
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

2233

被折叠的 条评论
为什么被折叠?



