POJ 1094-Sorting It All Out(拓扑排序)
来源:互联网 发布:淘宝金小姐正品代购 编辑:程序博客网 时间:2024/06/17 18:18
题目地址:POJ 1094
题意:题目样例的三种输出分别是:1. 在第x个关系中可以唯一的确定排序,并输出。2. 在第x个关系中发现了有回环(Inconsisitency矛盾)3.全部关系都没有发现上面两种情况,输出第3种.
思路:注意两点1. 输入一条边时如果此时拓扑有解就输出这个解,即使后面的边成有向环也不管了,所以每次输入的时候都得进行拓扑排序。2. 判断存在有向环应先于判断多解。
#include <stdio.h>#include <math.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <sstream>#include <algorithm>#include <set>#include <queue>#include <stack>#include <map>#pragma comment(linker, "/STACK:102400000,102400000")using namespace std;typedef __int64 LL;const int inf=0x3f3f3f3f;const double pi= acos(-1.0);const double esp=1e-7;const int Maxn=20010;struct node { int u,v,next;} edge[Maxn];int head[30];int in[30],ans[30],IN[30];int n,m,cnt,sum;void add(int u,int v){ IN[v]++; edge[cnt].u=u; edge[cnt].v=v; edge[cnt].next=head[u]; head[u]=cnt++;}int topo(){ int i; queue<int >q; for(i=0; i<n; i++) { in[i]=IN[i]; } for(i=0; i<n; i++) { if(!in[i]) q.push(i); } sum=0; int flag=0; if(q.size()>1) flag=1; while(!q.empty()) { int u=q.front(); q.pop(); ans[sum++]=u; for(i=head[u]; i!=-1; i=edge[i].next) { int v=edge[i].v; in[v]--; if(in[v]==0) q.push(v); } if(q.size()>1) flag=1; } if(sum!=n) return 2; else if(flag) return 1; return 3;}int main(){ int i,j; char str[5]; while(~scanf("%d %d",&n,&m)) { if(!n&&!m) break; memset(IN,0,sizeof(IN)); memset(in,0,sizeof(in)); memset(head,-1,sizeof(head)); int flag = 0; cnt = 0; int temp; int p; for(i=0; i<m; i++) { scanf("%s",str); if(flag) continue; add(str[0]-'A',str[2]-'A'); temp = topo(); if(temp==2||temp==3) { flag = 1; p = i + 1; } } if(flag) { if(temp==3) { printf("Sorted sequence determined after %d relations: ",p); for(i=0; i<n; i++) { printf("%c",ans[i]+'A'); } printf(".\n"); } else if(temp==2) { printf("Inconsistency found after %d relations.\n",p); } } else printf("Sorted sequence cannot be determined.\n"); } return 0;}
1 0
- POJ 1094 Sorting It All Out(拓扑排序)
- Poj 1094-Sorting It All Out [拓扑排序]
- POJ 1094-Sorting It All Out 拓扑排序
- zoj 1060 || 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 拓扑排序
- 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 拓扑排序+Floyd算法
- POJ 1094 Sorting It All Out (拓扑排序) - from lanshui_Yang
- 设计模式之 工厂模式
- javaweb学习总结(十)——HttpServletRequest对象(一)
- 必须记住的30类选择器
- SpringMVC Controller 介绍
- 数论 - hdu5363 Key Set
- POJ 1094-Sorting It All Out(拓扑排序)
- 多线程 读取List
- 图结构练习——判断给定图是否存在合法拓扑序列
- ICP算法与RANSAC算法描述
- Android Fragment 真正的完全解析(下)
- 第1章 计算机系统概论--笔记
- width:100%
- Linux笔记--目录
- Geos库在Windows上的编译