HDU 3760-Ideal Path bfs
来源:互联网 发布:linux安装service命令 编辑:程序博客网 时间:2024/05/01 04:54
题意:先给出一个t代表几组样例,n个点m条边,每条边有一个数字代表颜色,找出从1到n路径最短且颜色序列字典序最小的路径,输出路径长度和依次经过的边的颜色。
从n出发bfs序遍历,对于每个节点k第一次走到k时记录长度和上一个点,当由其他节点走到k时如果长度相等且上一节点的颜色数字更小时,更新k;如果k的前一节点为m,则保证了第一条边是字典序最小的,一直走到1结束。最后用dfs输出结果。
#include <iostream>#include <cstdio>#include <cstring>#include <map>#include <set>#include <queue>#include <stack>using namespace std;struct node { int l, d; node() {} node(int l, int d):l(l), d(d) {}};struct node2 { int l, d, nm;}id[100005];bool operator < (const node &a, const node &b) { if(a.d != b.d) return a.d < b.d; return a.l < b.l;}set<node> mp[100005];set<node>::iterator p;void deal(int n) { queue<int> q; memset(id, -1, sizeof(id)); id[n].l = 0; id[n].d = 0; id[n].nm = 0; q.push(n); int a; while(!q.empty()) { a = q.front(); q.pop();// printf("## %d\n", a); for(p = mp[a].begin(); p != mp[a].end(); p++) { if(id[p->l].d == -1 || (id[p->l].nm == id[a].nm + 1 && id[p->l].d > p->d)) { if(id[p->l].d == -1) q.push(p->l); id[p->l].l = a; id[p->l].d = p->d; id[p->l].nm = id[a].nm+1; } } }}int is;void dfs(int u, int n) { if(u == -1) { printf("error!\n"); for(;;); return; } if(u == n) return; if(is) printf(" "); else is = 1; printf("%d", id[u].d); dfs(id[u].l, n);}int main() { int t, n, m, a, b, c, i, j; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); for(i = 0; i < 100005; i++) { mp[i].clear(); } for(i = 0; i < m; i++) { scanf("%d%d%d", &a, &b, &c); mp[a].insert(node(b, c)); mp[b].insert(node(a, c)); } deal(n); printf("%d\n", id[1].nm); is = 0; dfs(1, n); printf("\n"); } return 0;}
注:这段代码虽然能够AC,但这个思路还是有一定问题的,当反向从n向1走时,如果走到一个点k的两条边的颜色数字式相同的就会无法确定两条路的字典序,因为实际上这种方式只判断了第一个数字。附样例:
1
6 6
1 2 1
1 4 1
2 3 3
4 5 2
3 6 2
5 6 2
0 0
- HDU 3760-Ideal Path bfs
- HDU 3760 Ideal Path 最短路+BFS
- HDU 3760 Ideal Path (bfs,分层)
- HDU 3760 Ideal Path
- HDU 3760 Ideal Path 最短路spfa+BFS 字典序最小的最短路
- HDOJ 3760: Ideal Path
- UVa 1599 - Ideal Path <两次BFS>
- UVa 1599 - Ideal Path(BFS)
- HDU3760 Ideal Path 逆bfs+贪心
- uva 1599 Ideal Path (两次bfs)
- hdu 3760 Ideal Path 字典序最小的最短路
- 例题6-20 UVa1599 Ideal Path(两次BFS)
- UVA 1599 Ideal Path 【两次BFS+贪心】 (好题)
- Ideal Path,uva1599/hdu 3760(最短路中字典序最小的路径)
- 1599 - Ideal Path
- uva 1599 - Ideal Path
- 1599 - Ideal Path
- UVa1599 - Ideal Path
- UniversalImageLoader源码解读02-图片处理和显示
- CronExpression
- 后缀数组的学习
- HTML解析利器HtmlAgilityPack - 小y
- Mesosphere公司即将发布DCOS1.7.0
- HDU 3760-Ideal Path bfs
- 问渠哪得清如许,唯有源头活水来-浅谈android 系统
- 关于数据库的一些问题收集(持续更新)
- pom.xml 配置详解
- Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)
- delphi superobject循环节点
- C++中的::操作符
- IOS开发中遇到的各种问题
- spring 根上下文和 spring dispatcherServlet 上下文的关系