我的第一个拓扑排序题。值得纪念一下,要注意的就是每输入一行就要TOPO一次。。。我开始吧整个图逗构建好了再去TOPO。。发现无法输出那个行数。。。。又要重新写。。悲剧啊。。。
#include<stdio.h>
#include<string.h>
#include<stack>
int judge[50][50];
char ans[27];
int sum[27];
int charge[27];
int temp[27];
int list[27],n,m;
int toposort(int p){
int cnt,yes=0,j,r;
r=0;
for(int i=0;i<n;i++){
temp[i]=sum[i];
}
while(p--){
cnt=0;
for(int i=0;i<n;i++){
if(temp[i]==0) j=i,cnt++;
}
//printf("C=%d\n",cnt);
if(cnt>=1){
if(cnt>1) yes=1;
for(int i=0;i<n;i++){
if(judge[j][i]==1) temp[i]--;
}
ans[r++]=j+'A';
temp[j]=-1;
ans[r]=0;
}
else if(cnt==0) return -1;
}
if(yes==0) return r;
else
return 0;
}
int main(){
int yes,num,k,de,t;
char a,b;
while(scanf("%d%d",&n,&m)!=EOF&&n!=0&&m!=0){
getchar();
memset(judge,0,sizeof(judge));
memset(sum,0,sizeof(sum));
memset(charge,0,sizeof(charge));
yes=0;
num=0;
de=0;
for(int i=1;i<=m;i++){
scanf("%c<%c",&a,&b);
getchar();
if(charge[a-'A']==0){
num++;
charge[a-'A']=1;
}
if(charge[b-'A']==0){
num++;
charge[b-'A']=1;
}
judge[a-'A'][b-'A']=1;
sum[b-'A']++;
if(judge[b-'A'][a-'A']==1){
yes=1;
k=i;
}
if(de==0&&yes==0){
t=toposort(num);
//printf("T%d\n",t);
if(t==-1){
de=-1;
k=i;
}
else if(t==n){
de=1;
k=i;
}
}
}
if(de==-1||yes==1){
printf("Inconsistency found after %d relations.\n",k);
}
else if(de==0){
printf("Sorted sequence cannot be determined.\n");
}
else{
printf("Sorted sequence determined after %d relations: %s.\n",k,ans);
}
}
return 0;
}