注意问题的转换,有环,无序,有序,还有他们的包含分界点
其中将字母装换成数字节点很妙
#include <stdio.h> #include <string.h> int map[27][27],indegree[27],q[27]; int n,m; int topsort() { int i,num,flag,j,start; int temp[27],c; c=0; flag=1; for(i=1;i<=n;i++) temp[i]=indegree[i]; for(i=1;i<=n;i++) { num=0; for(j=1;j<=n;j++) { if(temp[j]==0) { num++; start=j; } } if(num==0) return 0; if(num>1) flag=-1; q[c++]=start; temp[start]=-1; for(j=1;j<=n;j++) { if(map[start][j]==1) temp[j]--; } } return flag; } int main() { char str[4]; int i,j,s; int singe; while(scanf("%d%d",&n,&m),n+m) { singe=0; memset(indegree,0,sizeof(indegree)); memset(map,0,sizeof(map)); for(i=1;i<=m;i++) { scanf("%s",str); if(singe)continue; int x=str[0]-'A'+1; int y=str[2]-'A'+1; map[x][y]=1; indegree[y]++; s=topsort(); if(s==0) { printf("Inconsistency found after %d relations.\n",i); singe=1; continue; } if(s==1) { printf("Sorted sequence determined after %d relations: ",i); singe=1; for(j=0;j<n;j++) printf("%c",q[j]+'A'-1); printf(".\n"); } } if(!singe) printf("Sorted sequence cannot be determined.\n"); } return 0; }