拓扑排序 ---- HDU 1285

代码如下;

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
const int maxn = 1000;
int in[maxn];
vector<int>V[maxn];

int main()
{
int n,m,x,y;
while(cin>>n>>m){
memset(in,0,sizeof(in));
for(int i=1;i<=n;i++) V[i].clear();
while(m--)
{
cin>>x>>y;
V[x].push_back(y);//构图
in[y]++;// 存入度
}

priority_queue<int,vector<int>,greater<int> > q;// 优先数列,小的先出
for(int i=1;i<=n;i++)
{
if(in[i]==0)
{

q.push(i);
}
}
int flag=1;
while(!q.empty())
{
int xx=q.top();q.pop();
if(flag)
{
cout<<xx;
flag=0;
}
else cout<<" "<<xx;
for(int i=0;i<(int)V[xx].size();i++)
{
in[V[xx][i]]--;
if(in[V[xx][i]]==0)
{
q.push(V[xx][i]);
}
}

}
cout<<endl;
}
return 0;
}

posted @ 2019-08-09 19:29  zw100  阅读(89)  评论(0编辑  收藏  举报