POJ 1094(拓扑排序)

题目链接:POJ 1094

解题思路:
基本的思路就是拓扑排序算法。需要注意的是环的判断优先于排序是否唯一的判断。

代码:

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

int n,m,a[30][30],degree[30],tmp[30],ans[30],cnt;

int topo()
{
    memcpy(tmp,degree,sizeof(degree));
    queue<int> q;
    for(int i=0;i<n;i++)
    {
        if(!tmp[i])
            q.push(i);
    }

    int flag=0;
    cnt=0;
    while(!q.empty())
    {
        if(q.size()>1)
            flag=1;

        int front=q.front();
        q.pop();
        ans[cnt++]=front;
        for(int i=0;i<n;i++)
        {
            if(a[front][i])
            {
                if(!(--tmp[i]))
                    q.push(i);
            }
        }
    }
    if(cnt!=n)
        return -1;
    else if(flag)
        return 0;
    return 1;
}

int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        if(!n&&!m)
            break;

        memset(a,0,sizeof(a));
        memset(degree,0,sizeof(degree));
        getchar();

        int res,flag=0,index;
        char ch1,op,ch2;
        for(int i=1;i<=m;i++)
        {
            scanf("%c%c%c", &ch1, &op, &ch2);
            if(!a[ch1-'A'][ch2-'A'])
            {
                a[ch1-'A'][ch2-'A']=1;
                degree[ch2-'A']++;
            }
            getchar();

            if(flag)
                continue;
            res=topo();
            if(res==1||res==-1)
                flag=1,index=i;
        }

        if(res==1)
        {
            printf("Sorted sequence determined after %d relations: ",index);
            for(int i=0;i<n;i++)
                printf("%c",ans[i]+'A');
            printf(".\n");
            flag=1;
        }
        else if(res==-1)
        {
            printf("Inconsistency found after %d relations.\n",index);
            flag=1;
        }
        else if(res==0)
        {
            printf("Sorted sequence cannot be determined.\n");  
        }
    }

    return 0;
}

你可能感兴趣的:(POJ 1094(拓扑排序))