POJ 1094(TopoSort)

来源:互联网 发布:mac重置管理员账户 编辑:程序博客网 时间:2024/05/22 02:10

POJ 1094


题意:该题题意明确,就是给定一组字母的大小关系判断他们是否能组成唯一的拓扑序列。是典型的拓扑排序,但输出格式上确有三种形式:

     1.该字母序列有序,并依次输出;

     2.该序列不能判断是否有序

     3.该序列字母次序之间有矛盾,即有环存在。

但是注意顺序,必须要先判断环,其次是无序,最后才是有序。

#include<iostream>#include<cstring>#include<cstdio>using namespace std;#define Max 30int gragh[Max][Max];int ingreed[Max];char ans[Max];int n,m;int TopoSort(){    int temp[Max],pos,flag = 1,all = 0;    for(int i = 0;i < n; i++)        temp[i] = ingreed[i];    for(int i = 0;i < n; i++){        int num = 0;        for(int j = 0;j < n; j++){            if(temp[j] == 0){                pos = j;                num++;            }        }        if(num == 0)            return 0;        if(num > 1) flag = -1;        temp[pos]  = -1;        ans[all++] = pos;        for(int j = 0;j < n; j++)            if(gragh[pos][j] == 1)                temp[j]--;    }    return flag;}int main(){    while(cin>>n>>m){        if(n == 0 && m == 0)            break;        memset(gragh,0,sizeof(gragh));        memset(ingreed,0,sizeof(ingreed));        char str[5];        int sign = 0;        for(int i = 1;i <= m; i++){            cin>>str;            if(sign) continue;            gragh[str[0] - 'A'][str[2] - 'A'] = 1;            ingreed[str[2] - 'A']++;            int s = TopoSort();            if(s == 0){                printf("Inconsistency found after %d relations.\n",i);                sign = 1;            }            else if(s == 1){                printf("Sorted sequence determined after %d relations: ",i);                for(int j = 0;j < n; j++)                    printf("%c",ans[j] + 'A' );                printf(".\n");                sign = 1;            }        }        if(!sign)            printf("Sorted sequence cannot be determined.\n");    }    return 0;}



0 0
原创粉丝点击