您的位置:首页 > 其它

poj 1094 Sorting It All Out 拓扑排序

2012-04-10 22:32 459 查看
拓扑排序方法:

 (1)从有向图中选择一个没有前驱(即入度为0)的顶点并且输出它.

 (2)从网中删去该顶点,并且删去从该顶点发出的全部有向边.

 (3)重复上述两步,直到剩余的网中不再存在没有前趋的顶点为止.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
int n, m, a[30][30], count[30], top, seq[30], c[30];
int Topo_order(){
int i, j, k, f=0;
top=-1;
for(i=0; i<n; i++)
if(c[i]==0){
if(top!=-1)f=1;
c[i]=top;top=i;
}
for(i=0; i<n; i++){
if(top==-1)return -1;
else {
j=top;top=c[top];
seq[i]=j;
for(k=0; k<n; k++)
if(a[j][k]&&(--c[k])==0){
if(top!=-1)f=1;
c[k]=top;top=k;
}
}
}
if(f)
return 0;
return 1;
}

int main(){
//freopen("1.txt", "r", stdin);
int i, j, tmp, flag;
char str[5];
while(scanf("%d%d", &n, &m)&&n){
flag=0;
memset(count, 0, sizeof(count));
memset(a, 0, sizeof(a));
for(i=1; i<=m; i++){
scanf("%s", str);
if(flag)continue;
a[str[0]-'A'][str[2]-'A']=1;
count[str[2]-'A']++;
memcpy(c, count, sizeof(count));
tmp=Topo_order();
if(tmp==1){
flag=1;
printf("Sorted sequence determined after %d relations: ", i);
for(j=0; j<n; j++)
printf("%c", 'A'+seq[j]);
printf(".\n");
}
else if(tmp==-1){
flag=1;
printf("Inconsistency found after %d relations.\n", i);
}
}
if(!flag)printf("Sorted sequence cannot be determined.\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: