poj 1270 Following Orders
来源:互联网 发布:人马一体 知乎 编辑:程序博客网 时间:2024/06/04 18:27
题意:每组数据两行,第一行给你变量列表,第二行给你约束关系,成对的x y, 就是x < y。求所有的拓扑排序结果。
思路:用拓扑排序的思想来DFS,造成拓扑排序结果不唯一的原因是,在某一步中同时存在多个入度为0的顶点,所以这时存在多种选择。题目要求按字典序输出,我们按字典序选择入度为0的顶点,得到的结果就是按字典序排列的。
代码:
#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <string>#include <sstream>using namespace std;const int maxn = 27;bool exist[maxn];//字母是否出现bool edge[maxn][maxn];//邻接矩阵int ind[maxn];//入度 vector<char> lista;//变量列表 vector<char> listb; //约束关系 char res[maxn];//输出结果 bool Input(){string s;char ch;lista.clear();listb.clear();getline(cin,s);if(s == "") return false;istringstream in1(s);while(in1>>ch) lista.push_back(ch);getline(cin,s);istringstream in2(s);while(in2>>ch) listb.push_back(ch);return true;}void Build(){memset(edge,0,sizeof(edge));memset(exist,0,sizeof(exist));memset(ind,0,sizeof(ind));for(int i = 0; i < lista.size(); i++){exist[lista[i]-'a'] = true;}for(int i = 0; i < listb.size(); i += 2){int u = listb[i] - 'a';int v = listb[i+1] - 'a';edge[u][v] = true;}//统计入度 for(int i = 0; i < maxn; i++) {for(int j = 0; j < maxn; j++){if(edge[i][j]) ind[j]++;}}}bool vis[maxn];//是否已经选用某一点 void Dfs(int d){if(d == lista.size()){res[d] = '\0';printf("%s\n",res);return;}for(int i = 0; i < maxn; i++){if(exist[i] && !vis[i] && ind[i] == 0){vis[i] = true;for(int j = 0; j < maxn; j++){if(edge[i][j] && i != j)ind[j]--;}res[d] = i + 'a';Dfs(d+1);vis[i] = false;for(int j = 0; j < maxn; j++){if(edge[i][j] && i != j)ind[j]++;}}}}void Solve(){Build();Dfs(0);}int main(){int cnt = 0;while(Input()){if(cnt) puts("");Solve();cnt++;}return 0;}
0 0
- POJ 1270 Following Orders
- poj 1270 Following Orders
- POJ 1270 Following Orders
- POJ-1270 Following Orders
- POJ 1270 Following Orders
- POJ 1270 Following Orders
- poj 1270 Following Orders
- poj 1270 Following Orders
- poj 1270 Following Orders
- POJ 1270 Following Orders
- POJ 1270 Following Orders
- POJ 1270 Following Orders
- poj 1270 Following Orders 拓扑
- POJ 1270 Following Orders 笔记
- POJ 1270 Following Orders (拓扑排序)
- POJ 1270 HOJ 1170 Following Orders
- POJ 1270 Following Orders 拓扑排序
- POJ 1270 Following Orders 拓扑排序
- 换博客啦~
- 关于SQL的几个使用技巧
- 改良EventBus
- 备用总结:VS2012 Restful 路由失效解决!
- RootTools.jar的api
- poj 1270 Following Orders
- 使用switch语句编程,根据输入的年份判断是否为闰年,根据输入的月份判断这月有多少天
- vs2003出现“此计算机上没有安装项目系统组件。请重新安装重新安装visual stdio”解决方法
- 详解在IOS后台执行
- How Many Tables hdu1213
- Java使用Base64编码
- 自测3. 数组元素循环右移问题
- hadoop实战基础篇(二)
- UVA442 - Matrix Chain Multiplication