UVa 208:Firetruck(DFS)
2015-09-11 16:02
477 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=842&page=show_problem&problem=144
题意:输入一个n(n≤20)(n \le 20)个结点的无向图以及某个结点k,按照字典序从小到大顺序输出从结点1到结点k的所有路径,要求结点不能重复经过。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
对输入的边先进行排序,然后进行DFS,这样可以保证路径是符合字典序的。要注意的是,首先要对结点1到结点k是否连通进行判断,否则会超时。连通性判断可以用并查集来实现。
代码:
题意:输入一个n(n≤20)(n \le 20)个结点的无向图以及某个结点k,按照字典序从小到大顺序输出从结点1到结点k的所有路径,要求结点不能重复经过。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
对输入的边先进行排序,然后进行DFS,这样可以保证路径是符合字典序的。要注意的是,首先要对结点1到结点k是否连通进行判断,否则会超时。连通性判断可以用并查集来实现。
代码:
#include <iostream> #include <algorithm> #include <fstream> #include <cstring> #include <vector> #include <queue> #include <cmath> #include <cctype> #include <stack> #include <set> using namespace std; const int maxn = 20 + 1, INF = 1e8; int e, ans, C, x, y; int v[maxn], f[maxn], path[maxn]; vector< int > vec[maxn]; int Find(int x) { if (f[x] != x) f[x] = Find(f[x]); return f[x]; } void DFS(int x, int deep) { if (x == e) { ++ans; for (int i = 0; i < deep; ++i) if (i < deep - 1) printf("%d ", path[i]); else printf("%d\n", path[i]); return; } int l = vec[x].size(); for (int i = 0; i < l; ++i) { if (!v[vec[x][i]]) { v[vec[x][i]] = 1; path[deep] = vec[x][i]; DFS(vec[x][i], deep + 1); v[vec[x][i]] = 0; } } } int main() { while (~scanf("%d", &e)) { ans = 0; memset(v, 0, sizeof(v)); for (int i = 1; i < maxn; ++i) { f[i] = i; vec[i].clear(); } while (scanf("%d%d", &x, &y), x || y) { if (Find(x) != Find(y)) f[f[x]] = f[y]; vec[x].push_back(y); vec[y].push_back(x); } printf("CASE %d:\n", ++C); if (Find(1) == Find(e)) { for (int i = 0; i < maxn; ++i) sort(vec[i].begin(), vec[i].end()); v[1] = 1; path[0] = 1; DFS(1, 1); } printf("There are %d routes from the firestation to streetcorner %d.\n", ans, e); } return 0; }
相关文章推荐
- 破釜沉舟
- hdu 5289 rmp+二分+枚举后界 or单调队列 ****
- 软件测试-测试的补充
- js实现的后台左侧管理菜单代码
- Android系统启动过程
- 微信生成公众号带参数二维码(一)
- Win32汇编获取窗体的mousehover消息
- PAT1021
- UICollectionView基础
- linux下防火墙iptables用法规则详解
- 哈希冲突解决之开放寻址法
- Maven学习笔记(四)——MyEclipse导入、创建&配置Maven工程
- WebKit.net最简单使用方法
- IOS 电商类app 第一版架构
- 访问修饰符
- inux下"没有设置 SVN_EDITOR...."错误解决方法
- 欢迎使用CSDN-markdown编辑器
- KVM CPU小测试
- malloc,free,new 函数的总结
- qml学习-----------按键消息处理