题意:是否唯一确定顺序,根据情况输出
#include <iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define N 30
int n,m;
int map[N][N],indegree[N],list[N];
int toposort(int n){
int in[N],flag,t,num;
memcpy(in,indegree,sizeof(indegree));//复制入度数组,以免对主函数中的indegree有影响
stack<int> s;
int i;
for(i=0;i<n;i++)
if(!in[i])
s.push(i);//所有入度为0的点入栈,如果这些点多于1的话,序列不确定
num=0;
flag=0;
while(!s.empty()){
if(s.size()>1)
flag=1; //序列不确定
t=s.top();
s.pop();
list[num++]=t; //记录出栈的数字
for(i=0;i<n;i++)
if(map[t][i])
if(--in[i]==0)
s.push(i); //入度为0的点入栈
}
if(num!=n)//不能拓扑排序,即有环
return 1;
else if(flag==1)//有多种排序方式,不能唯一确定
return 2;
return 0;//序列能够被唯一确定
}
int main(int argc, char** argv) {
int determined,inconsistency;
int i,j,res;
// freopen("in.txt","r",stdin);
char a,b;
while(scanf("%d%d",&n,&m)&&n||m){
getchar();
determined=0;
inconsistency=0;
memset(map,0,sizeof(map));
memset(indegree,0,sizeof(indegree));
for(i=1;i<=m;i++){
scanf("%c<%c",&a,&b);
getchar();
if(!determined&&!inconsistency){
if(map[b-'A'][a-'A']==1){
inconsistency=1;
printf("Inconsistency found after %d relations.\n",i);
continue;
}
if(map[a-'A'][b-'A']==0){
map[a-'A'][b-'A']=1;
indegree[b-'A']++;
}
res=toposort(n);
if(res==0){
printf("Sorted sequence determined after %d relations: ",i);
for(j=0;j<n;j++)
printf("%c",list[j]+'A');
printf(".\n");
determined=1;
}
else if(res==1){
inconsistency=1;
printf("Inconsistency found after %d relations.\n",i);
}
}
}
if(!determined&&!inconsistency)
printf("Sorted sequence cannot be determined.\n");
}
return 0;
}