poj 1094 (拓扑排序,注意三种情况出现的优先级)

来源:互联网 发布:手机淘宝掌柜热卖截图 编辑:程序博客网 时间:2024/04/28 09:52

总结:

wa了多次,问题在于:当序列有多种拓扑顺序且还有环存在时,输出的结果应该为有环存在的情况。(Inconsistency found)

code中:

1-可以确定序列;

2-存在环,即:Inconsistency

3-多种拓扑顺序(多个入度为0的点),无法确定序列顺序


#include <iostream>#include <cstdio>#include <cstring>#include <stack>using namespace std;typedef struct node{    int to;    struct node * nptr;}node;stack<int> S;node * h[30];int n, m;int ind[30];char alph[30];int tot;void print(int flag, int k){    if(flag==1)    {        cout<<"Sorted sequence determined after "<<k+1<<" relations: ";        for(int i=0;i<tot;i++) cout<<alph[i];        cout<<".\n";    }    else if(flag==2)        cout<<"Inconsistency found after "<<k+1<<" relations.\n";}int topsort(){    int u, cnt=0;    int indcpy[30];    for(int i=0;i<n;i++)    {        indcpy[i]=ind[i];        if(indcpy[i]==0)        {            cnt++;            S.push(i);        }    }    bool flag=true;    if(cnt>1) flag=false;    tot=0;    for(int i=0;i<n;i++)    {        cnt=0;        if(S.empty()) return 2;        u=S.top(); S.pop();        node * ptr=h[u];        alph[tot++]=u+'A';        while(ptr)        {            indcpy[ptr->to]--;            if(indcpy[ptr->to]==0) {cnt++; S.push(ptr->to);}            ptr=ptr->nptr;        }        if(cnt>1) flag=false;    }    if(flag) return 1;    else return 3;}int main(){    char str[5];    node * ptr;    int u,v;    int flag;    //freopen("out.txt","w",stdout);    //freopen("in.txt","r",stdin);    while(1)    {        cin>>n>>m;        if(n==0 && m==0) break;        memset(h,0,sizeof(h));        memset(ind,0,sizeof(ind));        flag=3;        //flag=1, determined relation; flag=2, circle; flag=3, multiple  zero degree point        for(int i=0;i<m;i++)        {            cin>>str;            if(flag==1 || flag==2) continue;            ptr=new node;            u=str[0]-'A'; v=str[2]-'A';            ptr->nptr=h[u]; h[u]=ptr;            ptr->to=v; ind[v]++;            flag=topsort();            print(flag,i);        }        if(flag==3) cout<<"Sorted sequence cannot be determined.\n";    }        return 0;}/*******6 6A<DB<CE<FB<AD<EA<BInconsistency found after 6 relations.********/


原创粉丝点击