拓扑排序模板
#include<stdio.h>
#include<string.h>
#include<string>
int map1[30][30],degree[30],p[30];
int tuopu(int n)
{
int i,j,k,b[30],x=0,flog=1;
for(i=1; i<=n; i++)
b[i]=degree[i];//建造备份
for(i=1; i<=n; i++)//n个定点
{
int m=0,k=0;
for(j=1; j<=n; j++)
{
if(b[j]==0)
{
m++;
k=j;
}
}
if(m==0)return 0;//检查是否有环
if(m>1)//检查入度为0的点有几个
{
flog=-1;
}
p[x++]=k;
b[k]=-1;//将入度为0的点入度设为-1
for(int s=1; s<=n; s++)
{
if(map1[k][s]==1)//将当前入度为0的点的连接点的入度减1
b[s]--;
}
}
return flog;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m),n!=0&&m!=0)
{
int i,j,k,flog=0;
char a[5];
memset(map1,0,sizeof(map1));
memset(p,0,sizeof(p));
memset(degree,0,sizeof(degree));
for(i=1; i<=m; i++)
{
scanf("%s",a);
if(flog==1)continue;
map1[a[0]-'A'+1][a[2]-'A'+1]=1;
degree[a[2]-'A'+1]++;
int t;
t=fun(n);
if(t==0)
{
printf("Inconsistency found after %d relations.\n",i);
flog=1;
}
if(t==1)
{
printf("Sorted sequence determined after %d relations: ",i);
for(int x=0; x<n; x++)
printf("%c",p[x]+'A'-1);
printf(".\n");
flog=1;
}
}
if(flog==0) printf("Sorted sequence cannot be determined.\n");
}
}