poj 1094 Sorting It All Out 拓扑排序
来源:互联网 发布:佳博网络打印机设置 编辑:程序博客网 时间:2024/05/17 08:43
题目:http://poj.org/problem?id=1094
题意:给定n个字母,和m个它们之间的偏序关系,判断是否可以排成一个全序序列,在第几条关系后能得出全序序列,或者得出有矛盾。否则最后输出无法判断
思路:拓扑排序,如果有环肯定无法排成全序序列。进行拓扑排序时,每次只能有一个点入度为0,否则无法判断。
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <vector>#include <map>#include <cmath>#include <string>#include <sstream>#include <cctype>#include <queue>using namespace std;typedef long long ll;const int N = 30;vector<int> G[N];int n, m, k;int degree[N], tmp[N], res[N];bool used[N];int toposort(){ queue<int> que; memcpy(tmp, degree, sizeof degree); for(int i = 0; i < n; i++) if(tmp[i] == 0) que.push(i); k = 0; bool f = false; while(! que.empty()) { int v = que.front(); que.pop(); res[k++] = v; if(! que.empty()) f = true; //入度为0的点不止一个,无法排出全序序列 for(int i = 0; i < G[v].size(); i++) { if(--tmp[G[v][i]] == 0) que.push(G[v][i]); } } if(k != n) return -1; if(f) return 0; else return 1;}int main(){ char a, b; while(scanf("%d%d", &n, &m), n || m) { memset(degree, 0, sizeof degree); bool found = false; for(int i = 0; i < m; i++) { scanf(" %c<%c", &a, &b); if(found) continue; int x = a - 'A', y = b - 'A'; degree[y]++; G[x].push_back(y); int r = toposort(); if(r == 1) { printf("Sorted sequence determined after %d relations: ", i + 1); for(int i = 0; i < k; i++) printf("%c", res[i] + 'A'); printf(".\n"); found = true; } else if(r == -1) { printf("Inconsistency found after %d relations.\n", i + 1); found = true; } } if(!found) printf("Sorted sequence cannot be determined.\n"); for(int i = 0; i < 26; i++) G[i].clear(); } return 0;}
0 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
- 指针和引用的区别
- 005 ZeroMQ REQ-<ROUTER-Dealer>-REP代理应答与请求
- 太空3D
- 欢迎使用CSDN-markdown编辑器
- pwnable之coin1
- poj 1094 Sorting It All Out 拓扑排序
- Fibonacci(POJ3070)
- PHP开源框架Laravel的安装与配置
- Android开发:Eclipse中Ctrl+O快捷键显示该java文件中所有变量及方法
- unix环境高级编程(第三版)中apue.h文件的配置问题
- 114. Flatten Binary Tree to Linked List
- Java集合框架之Set--HashSet源码分析
- 利用贝塞尔曲线实现小球曲线运动
- MySQL 使用方法简单教程