D
e
s
c
r
i
p
t
i
o
n
\color{blue}{Description}
Description
有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
I
n
p
u
t
\color{blue}{Input}
Input
输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。
O
u
t
p
u
t
\color{blue}{Output}
Output
给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。
其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。
S
a
m
p
l
e
I
n
p
u
t
\color{blue}{Sample Input}
SampleInput
4 3
1 2
2 3
4 3
S
a
m
p
l
e
O
u
t
p
u
t
\color{blue}{Sample Output}
SampleOutput
1 2 4 3
import java.util.Scanner;
public class Main{
/*
* [7.20~7.26] 图的基本应用
* A - 确定比赛名次 hdu1285
* 拓扑排序
*/
static int n,m,N=505,x,y;
static int a[],g[][],degree[],output[];
static boolean dp[],vis[];
public static void main(String []args) {
Scanner sc=new Scanner(System.in);
g=new int [N][N];
degree=new int [N];
output=new int [N];
while(sc.hasNext()) {
init();
n=sc.nextInt();
m=sc.nextInt();
for(int i=1;i<=m;i++) {
x=sc.nextInt();
y=sc.nextInt();
if(g[x][y]==0) {
g[x][y]++;
degree[y]++;//入度+1
}
}
int cnt=0;
while(true) {
int j=1;
//找出当前序列的第一名。即入度为0的点。
if(degree[j]!=0) {
while(true) {
j++;
if(degree[j]==0||j>n) break;//
}
}
//找到当前序列的第一名后,将其标记为-1.表示已遍历过。
degree[j]=-1;
//记录下点的编号,为输出做准备.
output[cnt++]=j;
if(cnt==n)break;
//当前点删除后,需要同时删掉与其相连的边。
for(int i=1;i<=n;i++) {
if(g[j][i]>0) {
degree[i]--;
g[j][i]=-1;
}
}
}
for(int i=0;i<cnt-1;i++) {
System.out.print(output[i]+" ");
}
System.out.println(output[cnt-1]);
}
}
static void init() {
for(int i=1;i<N;i++) {
degree[i]=0;
output[i]=0;
for(int j=0;j<N;j++) {
g[i][j]=0;
}
}
}
}
/*
4 3
1 2
2 3
4 3
1 2 4 3
*/