zoukankan      html  css  js  c++  java
  • 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.
    ");
            else if(ok==1) printf("Sorted sequence determined after %d relations: %s.
    ",k,ans);
            else printf("Inconsistency found after %d relations.
    ",k);
        }
        return 0;
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

  • 相关阅读:
    ASP.NET 自制时间控件
    ORACLE 函数汇总之单记录函数
    Servers IIS 重启命令
    ASP.NET 两个Dropdownlist控件联动
    ASP.NET datagridview控件表头定义
    python Image 安装
    ssh 不需要密码的链接
    [Redis] redis 相关的博客
    [emacs] python代码折叠
    linux python 链接 oracle
  • 原文地址:https://www.cnblogs.com/xryz/p/4847906.html
Copyright © 2011-2022 走看看