您的位置:首页 > 其它

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输出结果。

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU-3760 BFS