有向无环图的拓扑排序 hdu 1285 确定比赛名次

Problem Description
有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。

Input
输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。

Output 给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。

其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。

Sample Input

4 3 1 2 2 3 4 3

Sample Output

1 2 4 3

我是用链式前向星存边的,用矩阵或邻接表都可以,随自己喜欢。
用优先队列+bfs实现,这里不可以用dfs,因为对于同一优先级的点来说,需要给它们进行排序,而dfs针对的主要是上下关系,bfs可以方便的排列同级关系。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <queue>
#include <math.h>
#include <bitset>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#include<functional>
#include<time.h>
#include<stdlib.h>
#include<time.h>
#include <climits>
using namespace std;
#define MEM(a,x) memset(a,x,sizeof(a))
#define gcd(a,b) __gcd(a,b)
#define ll long long
#define EXP 1e-8
#define lowbit(x) (x&-x)
#define debug(x) cout<<x<<"#";
const int maxn = 1e6;
int n, m;
int ct[maxn];
struct Edge {
	int w, to, next;
}edge[maxn];
int head[maxn],cnt;
int num[maxn],num1[maxn];
void init()
{
	for (int i = 0; i < maxn; i++)
	{
		head[i] = -1;
		edge[i].next = -1;
		num[i] = -1;
		num1[i] = 0;
		ct[i] = 0;
	}
	cnt = 0;
}
void addedge(int u, int v, int w)
{
	edge[cnt].to = v;
	edge[cnt].w = w;
	edge[cnt].next = head[u];
	head[u] = cnt++;
}
priority_queue<int,vector<int>,greater<int> > p1;
//queue<int>p1;

void bfs()
{
	cnt = 0;
	while (!p1.empty())
	{
		int l = 0;
		int u = p1.top();
	//	cout << u << endl;
		for (int i = head[u]; ~i; i =edge[i].next)
		{			
			--num[edge[i].to];
			if (!num[edge[i].to])
			{
				ct[l++] = edge[i].to;
			}
			
		}
		num1[cnt++] = p1.top();
		p1.pop();
		for (int i = 0; i < l; i++)
			{
				p1.push(ct[i]);
			}
			
	}
	return;
}
int main()
{
	while (cin >> n >> m)
	{
		init();
		for (int i = 1; i <= n; i++)
			num[i] = 0;
		for (int i = 0; i < m; i++)
		{
			int p1, p2;
			cin >> p1 >> p2;
			addedge(p1, p2, 0);  //p1指向p2
			num[p2]++;
		}
		for (int i = 1; i <= n; i++)
		{
			if (num[i] == 0)
			{
				p1.push(i);
			}
		}
		bfs();
		for (int i = 0; i < cnt-1; i++)
			cout << num1[i] << ' ';
		cout << num1[cnt-1] << endl;
	}
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值