确定比赛名次
Problem Description
有N个比赛队
(
1
<
=
N
<
=
500
)
(1<=N<=500)
(1<=N<=500),编号依次为
1
,
2
,
3
,
。
。
。
。
,
N
1,2,3,。。。。,N
1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
Input
输入有若干组,每组中的第一行为二个数N
(
1
<
=
N
<
=
500
)
,
M
(1<=N<=500),M
(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
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 505;
int node[maxn],e[maxn],ne[maxn],tot; //邻接表
int indeg[maxn];//入度
int n,m;
int add(int a,int b) //添加一条a -> b的边
{
e[tot] = b;
ne[tot] = node[a];
node[a] = tot++;
}
void topsort()
{
vector<int> res; //保存结果
priority_queue<int,vector<int>,greater<int>> Q; //小顶(跟)堆
for(int i=1;i<=n;++i) //找到所有的入度为0的点 ,入队
if(indeg[i] == 0)
Q.push(i);
while(Q.size()) //当队列不空
{
int f = Q.top(); //取队头
Q.pop(); //出队
res.push_back(f); //保存结果
for(int i=node[f];i!=-1;i=ne[i]) //遍历当前节点的每一条出边
{
int j = e[i]; //获取当前节点的编号
if(--indeg[j] == 0) //如果当前的节点入度为0,入队
Q.push(j);
}
}
int len = res.size();
for(int i=0;i<len;++i)
printf("%d%c",res[i]," \n"[i==len-1]); //奇技淫巧输出
}
int main()
{
while(~scanf("%d%d",&n,&m)) //多组输入
{
memset(node,-1,sizeof node);
memset(indeg,0,sizeof indeg); //初始化
tot = 0;
int a,b;
while(m--)
{
scanf("%d%d",&a,&b);
add(a,b);
indeg[b] ++; //b入度增加1
}
topsort();
}
return 0;
}