poj 1094 Sorting It All Out

/* Name:poj 1094 Sorting It All Out Author: UnimenSun Date: 21/05/2011 14:08 Description: 拓扑排序 */ /* 解题报告:拓扑排序 拓扑排序基本方法: 1、从有向图中选取一个没有前驱的顶点,并处理之(可以存或输出) 2、从有向图中删去此顶点以及所有以它为尾的弧 重复上述两步,直至图空,或者图中找不到无前驱的顶点为止 注:没有前驱:入度为0;删除顶点和以它为尾的弧:弧头顶点的入度减1 */ #include <iostream> #include <cstring> #include <string> using namespace std; const int MAXN = 30; int n, m; bool graph[MAXN][MAXN]; //graph[i][j]=1 表示j的前驱为i char order[MAXN]; int topsort() { int i, j, k; int indegree[MAXN]; //存储入度的数组 bool bFlag = true; memset(order, 0, sizeof(order)); //初始化入度数组 memset(indegree, 0, sizeof(indegree)); for(i=1; i<=n; ++i) { for(j=1; j<=n; ++j) { if(graph[i][j] == true) indegree[j]++; } } for(k=1; k<=n; ++k) { i = 0; for(j=1; j<=n; ++j) { if(0 == indegree[j]) //入度为0的 { if(0==i) i=j; else bFlag = false; } } if(0 == i) return 1; //不存入度为0的点,即图中存在环,这时的拓扑排序是失败的 indegree[i]--; //将入度为0的减1,避免下次再找到该点 order[k-1] = i + 'A' - 1; for(j=1; j<=n; ++j) { if(graph[i][j]) indegree[j]--; } } if(bFlag) return 2; else return 3; //确定不了拓扑排序,即图中存在多个入度为0的点 } int main() { int i; string szInput; bool bFlag; while(cin>>n>>m && (n!=0 || m!=0)) { //初始化graph,刚开始全部为假 memset(graph, false, sizeof(graph)); bFlag = false; for(i=1; i<=m; ++i) { cin>>szInput; int a = szInput[0] - 'A' + 1; int b = szInput[2] - 'A' + 1; graph[a][b] = true; if(bFlag) continue; int result = topsort(); if(1 == result) { cout<<"Inconsistency found after "<<i<<" relations."<<endl; bFlag = true; } else if(2 == result) { cout<<"Sorted sequence determined after "<<i<<" relations: "<<order<<"."<<endl; bFlag = true; } } if(bFlag == false) cout<<"Sorted sequence cannot be determined."<<endl; } return 0; }

你可能感兴趣的:(poj 1094 Sorting It All Out)