HDU 3760-Ideal Path bfs
2016-05-11 17:09
134 查看
题意:先给出一个t代表几组样例,n个点m条边,每条边有一个数字代表颜色,找出从1到n路径最短且颜色序列字典序最小的路径,输出路径长度和依次经过的边的颜色。
从n出发bfs序遍历,对于每个节点k第一次走到k时记录长度和上一个点,当由其他节点走到k时如果长度相等且上一节点的颜色数字更小时,更新k;如果k的前一节点为m,则保证了第一条边是字典序最小的,一直走到1结束。最后用dfs输出结果。
注:这段代码虽然能够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
从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 .l = 0; id .d = 0; id .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
相关文章推荐
- Surrounded Regions
- Word Ladder, Gray Code
- UVA 11624
- HDU1495
- HDU2612 Find a way
- HDU1241 Oil Deposits
- Hdu2444二分图
- 最少步数BFS
- 转v_JULY_v的 BFS和DFS优先搜索算法
- 2015 寒假搜索专题 I - Meteor Shower(BFS)
- Same Tree
- E - Roads in the North
- DFS&BFS算法总结(1)
- Word Ladder I
- 图的BFS和DFS学习笔记
- [LeetCode] Binary Tree Level Order Traversal
- [LeetCode] Binary Tree Level Order Traversal II
- 关于BFS搜索的思想, 最简单的水题,不过深有体会啊。
- Word Ladder II
- Surrounded Regions