HDU 1285 确定比赛名次

题目地址

题意:

输出一副有向无环图的拓扑排序。当结果不唯一时,要求较小的编号在前。

思路:

采用优先队列的标准拓扑排序即可。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+5;

int main()
{
	int n,m;
	while(cin>>n>>m)
	{
		vector<int> G[505];
		int in[505]={0};
		for(int i=1;i<=m;++i)
		{
			int x,y;
			cin>>x>>y;
			G[x].push_back(y);
			++in[y];
		}
		priority_queue<int,vector<int>,greater<int> > pq;
		for(int i=1;i<=n;++i)
			if(!in[i])
				pq.push(i);
		while(!pq.empty())
		{
			int t=pq.top();
			pq.pop();
			for(int i:G[t])
			{
				--in[i];
				if(!in[i])
					pq.push(i);
			}
			cout<<t;
			if(!pq.empty())
				cout<<" ";
			else
				cout<<"\n";
		}
	}
}
posted @ 2023-01-01 21:15  ice_dragon_grass  阅读(74)  评论(0)    收藏  举报