拓扑排序(poj1094)Sorting It All Out

#include <iostream>
#include <string>
using namespace std;

int indegree[27];//入度
int map[27][27];//图
int q[27];//解空间

int TopoSort(int n)//拓扑排序
{
    int count=0;//记录解空间中零入度顶点的个数
    int temp[27];//对入度顶点备份
    int loc;//记录一个零入度顶点的数目
    int i,j;
    int m;//零入度顶点的个数
    int flag=1;//flag=1:有序  flag=-1:不能确定
    for (i=1;i<=n;i++)
    {
        temp[i]=indegree[i];//备份
    }
    for (i=1;i<=n;i++)
    {
        m=0;
        for (j=1;j<=n;j++)//查找零入度顶点的个数
        {
            if (temp[j]==0)
            {
                m++;
                loc=j;//记录一个零入度顶点的位置
            }
        }
        if (m==0)//零入度顶点的个数==0:有环
        {
            return 0;
        }
        if (m>1)//零入度顶点的个数>1:无序
        {
            flag=-1;//当知道无序时,并不一定知道该图是否有环,因此要继续执行程序,可别急着退出...
        }
        q[count++]=loc;//零入度顶点入队
        temp[loc]=-1;//将零入度顶点的入度置为-1
        for (j=1;j<=n;j++)//删除以loc为起点的边
        {
            if (map[loc][j]==1)
            {
                temp[j]--; //相应定点的入度减1
            }
        }      
    }
    return flag;
}
int main()
{
 freopen("in.txt","r",stdin);
    int n,m;
    int sign;//当sign=1时,程序已经得出结果,不需再考虑后面的输入
    string str;
    while (scanf("%d%d",&n,&m) && n!=0 && m!=0)
    {
        memset(map,0,sizeof(map));
        memset(indegree,0,sizeof(indegree));
        sign=0;
        for (int i=1;i<=m;i++)
        {
            cin>>str;
            if (sign)
            {
                continue;//一旦得出结果,对后续的输入置之不理!
            }
            int u=str[0]-'A'+1;
            int v=str[2]-'A'+1;
            map[u][v]=1;
            indegree[v]++;
            int s=TopoSort(n);
            if (s==0)//有环
            {
                printf("Inconsistency found after %d relations.\n",i);
                sign=1;
            }
            if (s==1) //有序
            {
                printf("Sorted sequence determined after %d relations: ",i);
                for (int j=0;j<n;j++)
                {
                    putchar(q[j]+'A'-1);//输出字符 putchar(ASCII)
                }
                printf(".\n");
                sign=1;
            }   
        }
        if(!sign)//无法得出结果
        {
            printf("Sorted sequence cannot be determined.\n");
        }
    }
    system("pause");
    return 0;
}

 

posted @ 2011-03-06 00:18  acm_poj  阅读(143)  评论(0)    收藏  举报