题目:POJ-1094
参考:POJ1094拓扑排序
利用拓扑排序判断有向图是否有环,在拓扑排序中判断无环图的入度为0的点是否有且只有一个,若为零,则有环,若大于一,则不确定
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int map[30][30],indegree[30];
int info;
int eng[30];
int n,m;
int topsort() {
int t,k,c=0,temp[30],flag=1;
for(int i=0; i<n; i++)
temp[i]=indegree[i];
for(int i=0; i<n; i++) {
t=0;
for(int j=0; j<n; j++)
if(!temp[j]) {
t++;
k=j;
}
if(t==0)
return 0;
if(t>1)
flag=2;
eng[c++]=k;
temp[k]=-1;
for(int j=0; j<n; j++)
if(map[k][j]) temp[j]--;
}
return flag;
}
int main() {
while(1) {
scanf("%d %d",&n,&m);
if(n==0&&m==0)
break;
memset(map,0,sizeof(map));
memset(indegree,0,sizeof(indegree));
info=0;
int j;
char s[4];
for(j=1; j<=m; j++) {
scanf("%s",s);
map[s[0]-'A'][s[2]-'A']=1;
indegree[s[2]-'A']++;
int u=topsort();
if(u!=2) {
if(u==1) {
printf("Sorted sequence determined after %d relations: ",j);
for(int i=0; i<n; i++)
printf("%c",eng[i]+'A');
printf(".\n");
} else
printf("Inconsistency found after %d relations.\n",j);
for(j++; j<=m; j++)
scanf("%s",s);
info=1;
break;
}
}
if(info)continue ;
printf("Sorted sequence cannot be determined.\n");
}
return 0;
}