杭电 1285 确定比赛名次(拓扑排序入门)

 传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1285

拓扑排序:按某种顺序输出没有前驱的点。

思路:题目即要求按字典序拓扑排序。

AC代码:

#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;

int n;
int par[505];//前驱
int ans[505];//记录答案 
bool chart[505][505];//记录两人是否进行比赛 

void Topo()
{
	int top,k=0;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(par[j]==0)
			{
				top=j;
				break;
			}
		}
		ans[++k]=top;
		par[top]--;
		for(int j=1;j<=n;j++)
		{
			if(chart[top][j]) par[j]--;
		}
	}
	for(int i=1;i<=n;i++)
		printf("%d%c",ans[i],i!=n?' ':'\n');
	return;
}
int main()
{
	int a,b,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		memset(par,0,sizeof(par));
		memset(chart,0,sizeof(chart));
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d",&a,&b);
			if(chart[a][b]==0)
			{
				chart[a][b]=1;
				par[b]++;
			}
		} 
		Topo();
	}
	return  0;
}

猜你喜欢

转载自blog.csdn.net/jack_jxnu/article/details/81503153
今日推荐