【备战蓝桥杯国赛-国赛真题】出差

题目链接:https://www.dotcpp.com/oj/problem2695.html

在这里插入图片描述

思路

为了方便,在建图的过程中,两个点之间的距离我们需要重新定义,即点x到y的距离再加上在点y需要进行隔离的时间,另外,题目中说明了目标点n的隔离时间不计,需要注意,处理的时候我们将点n的隔离时间标记为0即可。

坑点:本题的代码最开始是使用堆优化版的Dijkstra写的,但是在dotcpp网站上总是有三个点超时,我百思不得其解,后来联系到了网站的管理员,想了解一些这三个测试数据的特点,但是管理员目前还没有回复我关于数据的问题,后来我在蓝桥杯官网上测试了本题的堆优化代码,全部通过(AC),我想着总是有三个点过不去,不大完美,后来增加了朴素版的Dijstra代码,最终在dotcpp上成功全部通过(AC)。

两份代码都会放在下面。

代码(C++)

  • 朴素版Dijkstra(dotcpp上AC)
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1010;

int n, m;
int g[N][N];
int dist[N], st[N], v[N];

int dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    for(int i = 0; i < n; i ++) {
        int t = -1;
        for(int j = 1; j <= n; j ++) {
            if(!st[j] && (t == -1 || (dist[j] < dist[t]))) {
                t = j;
            }
        }

        if(t == -1) break;
        for(int j = 1; j <= n; j ++)
            dist[j] = min(dist[j], dist[t] + g[t][j]);
        st[t] = true;
    }

    return dist[n];
}

int main() {
    cin >> n >> m;
    for(int i = 1; i <= n; i ++) cin >> v[i];
    v[n] = 0;

    memset(g, 0x3f, sizeof g);
    while(m --) {
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = c + v[b];
        g[b][a] = c + v[a];
    }

    cout << dijkstra() << "\n";
    return 0;
}
  • 堆优化版Dijstra(蓝桥杯官网上AC了)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

typedef pair<int, int> PII;

const int N = 1010, M = 20010;

int n, m;
int h[N], e[M], ne[M], w[M], idx;
int v[N], dist[N], st[N];

void add(int a, int b, int c) {
    c += v[b];
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

int dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, 1});

    while(heap.size()) {
        auto t = heap.top(); heap.pop();

        int node = t.second;

        if(st[node]) continue;
        st[node] = true;

        for(int i = h[node]; i != -1; i = ne[i]) {
            int j = e[i];
            if(dist[j] > dist[node] + w[i]) {
                dist[j] = dist[node] + w[i];
                heap.push({dist[j], j});
            }
        }
    }

    return dist[n];
}

int main() {
    cin >> n >> m;
    for(int i = 1; i <= n; i ++) cin >> v[i];
    v[n] = 0;

    memset(h, -1, sizeof h);
    while(m --) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }

    if(n == 1) {
        cout << 0 << "\n";
        return 0;
    }

    cout << dijkstra() << "\n";
    return 0;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值