拓扑排序
来源:互联网 发布:ifconfig mac地址 编辑:程序博客网 时间:2024/04/29 12:59
【题目地址】POJ1094
【题目大意】题目意思比较容易理解,我就不在这里多说了。
【题目分析】该题需要利用拓扑排序进行处理
【代码】
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <stack>#define mem(x) memset((x),0,sizeof((x)))const int N=30;using namespace std;int graph[N][N];int indegree[N];int list[N];int toposort(int n) { int in[N]; memcpy(in,indegree,sizeof(indegree)); //复制入度数组,以免对主函数中的indegree有影响 stack<int> s; int i; for(i=0; i<n; i++) if(!in[i]) s.push(i);//所有入度为0的点入栈,如果这些点多于1的话,序列不确定 int flag=0; int t,j=0; while(!s.empty()) { if(s.size()>1) flag=1; //序列不确定 t=s.top(); s.pop(); list[j++]=t; //记录出栈的数字 for(i=0; i<n; i++) if(graph[t][i]) if(--in[i]==0) s.push(i);//入度为0的点入栈 } if(j!=n)//不能拓扑排序,即有环 return 1; else if(flag==1)//有多种排序方式,不能唯一确定 return 2; return 0;//序列能够被唯一确定}int main(){ freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int n,m; int determined,Inconsistency; int res; char a,b; while(scanf("%d%d",&n,&m) != EOF && n+m){ getchar(); mem(graph); mem(indegree); determined = 0; Inconsistency = 0; for(int i = 1; i <= m; i++){ scanf("%c<%c",&a,&b); getchar(); if(!determined && !Inconsistency){ if(graph[b-'A'][a-'A'] == 1){ Inconsistency = 1; printf("Inconsistency found after %d relations.\n",i); continue; } if(graph[a-'A'][b-'A'] == 0){ graph[a-'A'][b-'A'] = 1; indegree[b-'A']++; } res = toposort(n); if(res == 0){ printf("Sorted sequence determined after %d relations: ",i); for(int j = 0; j < n; j++){ printf("%c",list[j] + 'A'); } printf(".\n"); determined = 1; } else if(res == 1){ printf("Inconsistency found after %d relations.\n",i); Inconsistency = 1; } } } if(!determined && !Inconsistency){ printf("Sorted sequence cannot be determined.\n"); } } return 0;}
【注】以上代码参考了博主 pushing my way 关于该题的解题代码
【后记】toposort函数我还是没怎么看懂
0 0
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 【拓扑排序】
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 解决[NSdata data]与实际时间相差八个小时的方案
- 李娜的《独自上场》
- ERP信息化管理软件的财务应用价值
- 将博客搬至CSDN
- 草原
- 拓扑排序
- Android虚拟机无法启动Failed to allocate memory: 8
- Reduced ID Numbers (memset 的关键用处)
- JDK中的设计模式
- 二叉搜索树的后序遍历序列和二叉搜索树的前序遍历序列
- UImageView添加事件
- redis支持的数据类型
- chapter9面向对象
- 设计模式在JAVA中的具体运用