zoj 1060 Sorting It All Out(拓扑排序)

#include<bits/stdc++.h>
using namespace std;

vector< vector<char> >v;
int n,m,use[30],cnt[30];
char ans[30],s[10];

int topsort(int x)
{
    int i,j,t[30],f=1,r,c;
    memset(ans,0,sizeof(ans));
    for(i=0; i<30; i++) t[i]=cnt[i];
    c=0;
    r=0;
    while(x--)
    {
        c=0;
        for(i=0; i<n; i++)
        {
            if(t[i]==0)
            {
                j=i;
                c++;
            }
        }
        if(c>=1)
        {
            if(c>1) f=0;
            for(i=0; i<v[j].size(); i++)
            {
                t[v[j][i]]--;
            }
            ans[r++]=j+'A';
            t[j]=-1;
            ans[r]=0;
        }
        else if(c==0)
            return -1;
    }
    if(f)
        return r;
    else
        return 0;
}

int main()
{
    int flag,i,num,ok,k;
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0&&m==0) break;
        v.clear();
        v.resize(n);
        memset(use,0,sizeof(use));
        memset(cnt,0,sizeof(cnt));
        ok=0;
        num=0;
        for(i=0; i<m; i++)
        {
            scanf("%s",s);
            cnt[s[2]-'A']++;
            v[s[0]-'A'].push_back(s[2]-'A');
            if(!use[s[0]-'A'])
            {
                num++;
                use[s[0]-'A']=1;
            }
            if(!use[s[2]-'A'])
            {
                num++;
                use[s[2]-'A']=1;
            }
            if(ok==0)
            {
                int t=topsort(num);
                if(t==n)
                {
                    ok=1;
                    k=i+1;
                }
                else if(t==-1)
                {
                    ok=-1;
                    k=i+1;
                }
            }
        }
        if(!ok) printf("Sorted sequence cannot be determined.\n");
        else if(ok==1) printf("Sorted sequence determined after %d relations: %s.\n",k,ans);
        else printf("Inconsistency found after %d relations.\n",k);
    }
    return 0;
}

你可能感兴趣的:(zoj 1060 Sorting It All Out(拓扑排序))