poj 1094 Sorting It All Out
2011-07-22 22:17
375 查看
// 题意:给出n个字母和一系列不等式,判断是否能确定所有字母顺序 // 输出在最早在第几个不等式处可以确定下唯一的顺序或判断出矛盾,或者到最后也无法确定唯一的顺序 #include<iostream> //拓扑排序 using namespace std; int table[26][26],path[26],in[26],origin_in[26]; //in表示入度数 int main() { char ch[4]; int n,m,a,b; while(cin>>n>>m&&n) { memset(table,0,sizeof(table)); memset(origin_in,0,sizeof(origin_in)); int done=0; for(int k=1;k<=m;++k) //每输入一组偏序关系进行一次拓扑排序 { scanf("%s",ch); if(done) //done=1表示找到回路或找到唯一的拓扑序列 continue; a=ch[0]-'A';b=ch[2]-'A'; table[a][b]=1; origin_in[b]++; //因为入度in的值在拓扑时会改变,所以需要记录原始的入度值 for(int i=0;i<n;++i) in[i]=origin_in[i]; int rear=0; int sole=1; //sole标记序列是否唯一:只有在拓扑排序过程中每次都只有一个顶点的入度为0,序列才能最终唯一 for(int i=0;i<n;++i) { if(in[i]==0) path[rear++]=i; } if(rear>1) sole=0; for(int i=0;i<rear;++i) { int add=0; for(int j=0;j<n;++j) { if(table[path[i]][j]==1) { in[j]--; if(in[j]==0) { path[rear++]=j; add++; } } } if(add>1) //序列不唯一 sole=0; } if(rear<n) //Inconsistency就是存在回路 { printf("Inconsistency found after %d relations.\n",k); done=1; } else if(sole==1) //序列唯一 { printf("Sorted sequence determined after %d relations: ",k); for(int i=0;i<rear;++i) printf("%c",path[i]+'A'); printf(".\n"); done=1; } } if(!done) //不存在回路也不存在唯一的拓扑序列,这要到最后才能判断出来 printf("Sorted sequence cannot be determined.\n"); } return 0; }
相关文章推荐
- [poj1094]Sorting It All Out_拓扑排序
- 拓扑排序 POJ 1094 Sorting It All Out
- POJ 1094 Sorting It All Out【floyd传递闭包+拓扑排序】
- poj1094——Sorting It All Out(拓扑排序)
- POj 1094 Sorting It All Out
- POJ 1094 Sorting It All Out【拓扑排序】
- POJ 1094-Sorting It All Out 拓扑排序
- POJ 1094 Sorting It All Out
- POJ1094 Sorting It All Out(拓扑排序)
- POJ 1094 Sorting It All Out(拓扑排序)
- POJ 1094 Sorting It All Out【拓扑排序】
- POJ 1094 Sorting It All Out (拓扑排序)
- 【POJ 1094】Sorting It All Out 【topo排序 的三种情况的特判】
- POJ 1094 Sorting It All Out(经典拓扑+邻接矩阵)
- poj 1094 Sorting It All Out (拓扑排序)
- POJ 1094 Sorting It All Out(拓扑排序)
- poj 1094--Sorting It All Out
- 拓扑排序 POJ 1094 Sorting It All Out
- POJ 1094 Sorting It All Out【拓扑排序】
- poj 1094 Sorting It All Out 拓扑排序