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
这是一道简单的拓扑结构排序题;
有个地方坑了我几次;
居然有重复的边;
#include<iostream>
#include<cstdlib>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stack>
#include<queue>
#include<iomanip>
#include<map>
#include<set>
#define pi 3.14159265358979323846
using namespace std;
int graph[600][600];
int indegree[600];
int ans[600];
int main()
{
int N,M;
while(scanf("%d %d",&N,&M)!=EOF)
{
memset(indegree,0,sizeof(indegree));
memset(graph,0,sizeof(graph));
int i,j;
int cnt=0;
for(int k=1;k<=M;++k)
{
scanf("%d %d",&i,&j);
//防止重复边
if(!graph[i][j])
{
graph[i][j]=1;
++indegree[j];
}
}
//基本拓扑排序
for(int k=1;k<=N;++k)
for(int t=1;t<=N;++t)
{
if(indegree[t]==0)
{
--indegree[t];
ans[cnt++]=t;
for(int p=1;p<=N;++p)
{
if(graph[t][p]) --indegree[p];
}
break;
}
}
for(int i=0;i<N;++i)
{
if(i==0)
printf("%d",ans[i]);
else
printf(" %d",ans[i]);
}
printf("\n");
}
return 0;
}