HDU 3760-Ideal Path bfs

题意:先给出一个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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值