其他分享
首页 > 其他分享> > poj 1094(拓扑排序,三种情况:1正好排好,2正好有环,3到最后也没排好,也没有环,多重解)

poj 1094(拓扑排序,三种情况:1正好排好,2正好有环,3到最后也没排好,也没有环,多重解)

作者:互联网

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,flag,edge[30][30],indegree[30],indgr_tmp[30],ans[30];
void topo(){
    int i,j,s,pos;
    for(i=0;i<n;i++){
        indgr_tmp[i] = indegree[i];
    }
    pos = 0;
    for(i=0;i<n;i++){
        s = 0;
        for(j=0;j<n;j++){
            if(indgr_tmp[j]==0){
                s++;
                pos = j;
            }
        }
        if(s==0){
            flag = 1;//环 
            return;
        }
        if(s>1){
            flag = -1;//有多重解 
        }
        ans[i] = pos;
        indgr_tmp[pos]=-1;
        for(j=0;j<n;j++){
            if(edge[pos][j]){
                indgr_tmp[j]--;
            }
        } 
    }
}
int main(){
    int m,i,j,sign;
    char a[1000][3];
    while(scanf("%d%d",&n,&m)==2&&n){
        sign = 0;
        memset(indegree,0,sizeof indegree);
        memset(edge,0,sizeof edge);
        for(i=0;i<m;i++){
            scanf("%s",a[i]);
            if(sign==1)continue;
            flag = 0;
            edge[a[i][0]-'A'][a[i][2]-'A'] = 1;
            indegree[a[i][2]-'A']++;
            memset(ans,0,sizeof ans);
            memset(indgr_tmp,0,sizeof indgr_tmp); 
            topo();
            if(flag==1){
                printf("Inconsistency found after %d relations.\n",i+1);
                sign = 1;
            }
            if(flag==0){
                printf("Sorted sequence determined after %d relations: ",i+1);
                for(j=0;j<n;j++){
                    printf("%c",ans[j]+'A');
                } 
                printf(".\n");
                sign = 1;
            }
        }
        if(flag==-1){
            printf("Sorted sequence cannot be determined.\n");
        }
    }
    return 0;
}

 

标签:1094,正好,int,30,pos,indgr,有环,ans,include
来源: https://www.cnblogs.com/stevenzrx/p/15134818.html