#include<string.h>
#include<stdio.h>
#include<malloc.h>
#define MAXN 10
struct ArcNode
{
int to;
struct ArcNode *next;
};
int n,m; //顶点个数和边数
struct ArcNode * List[MAXN];
int count[MAXN];
char output[100];
void TopSort()
{
int j, i,k,len,top=-1;
struct ArcNode *temp;
int bcycle=0;
int pos=0;
for(i=0;i<n;i++)
{
if(count[i]==0)
{
count[i]=top;
top=i;
}
}
for(i=0;i<n;i++)
{
if(top==-1)
{
bcycle=1;
break;
}
else
{
j=top;
top=count[j];
pos+=sprintf(output+pos,"%d",j+1);
temp=List[j];
while(temp!=NULL)
{
k=temp->to;
if(--count[k]==0)
{
count[k]=top;
top=k;
}
temp=temp->next;
}
}
}
if(bcycle)
printf("has a cycle!\n");
else
{
len=strlen(output);
output[len]=0;
printf("%s",output);
}
}
int main()
{
int i,u,v;
struct ArcNode * temp;
while(1)
{
scanf("%d%d",&n,&m);
if(n==0&&m==0)
break;
memset(List,0,sizeof(List));
memset(count,0,sizeof(count));
memset(output,0,sizeof(output));
for(i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
u--;
v--;
count[v]++;
temp=(struct ArcNode *)malloc(sizeof(struct ArcNode));
temp->to=v;
temp->next=NULL;
if(List[u]==NULL)
List[u]=temp;
else
{
temp->next=List[u]->next;
List[u]->next=temp;
}
}
TopSort();
for(i=0;i<n;i++)
{
temp=List[i];
while(temp!=NULL)
{
List[i]=temp->next;
free(temp);
temp=List[i];
}
}
}
return 0;
}
对输入的有向图进行拓扑排序
最新推荐文章于 2023-09-04 15:59:19 发布