#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 拓扑排序裸题
最新推荐文章于 2017-06-08 20:45:27 发布