此题是拓扑排序的典型例子!如果一个队没有前驱就选择,然后去掉以这个点为前驱的点.
代码:
#include<stdio.h>
#include<string.h>
struct team{
int e,next;
}ar[20000];
int n,fb[505],num[505];
int search(){//找没有前驱的点
int i;
for(i=1;i<=n;i++){
if(fb[i]==0)
{
fb[i]=-1;
return i;
}
}
return 1;
}
void f(int x){//去掉以这个点为前驱的边
int i,j,k;
for(i=1;i<=n;i++){
if(fb[i] && fb[i]!=-1){
while(x==ar[fb[i]].e)
{
fb[i]=ar[fb[i]].next;
}
k=fb[i];
for(j=ar[fb[i]].next;j;j=ar[j].next){
if(ar[j].e==x){
ar[k].next=ar[j].next;
continue;
}
k=j;
}
}
}
}
void make(){
int i,x;
for(i=0;i<n-1;i++){
x=search();
printf("%d ",x);
f(x);
}
x=search();
printf("%d\n",x);
}
int main(){
int m,i,x,y;
while(scanf("%d%d",&n,&m)!=EOF){
memset(fb,0,sizeof(fb));
for(i=1;i<=m;i++){
scanf("%d%d",&x,&y);
ar[i].e=x;ar[i].next=fb[y];fb[y]=i;
}
make();
}
return 0;
}