2026/07/03 模拟赛 B

· · 题解

旅行 / Travel

题意简述

在一个 n \times m 的网格上,有 k 个点。已知每个点的位置和价值,求一条 (1, 1) 到 (n, n) 的最短路径上的最大价值。

题目分析

首先考虑最短路径的含义。即所涉及到的点满足二维偏序。

暴力DP

考虑朴素DP:

上述算法时间复杂度 O(k^2),期望得分 40 分。

树状数组优化DP

考虑优化:

上述算法时间复杂度 O(k\text{ }log_2\text{ }k),期望得分 100 分,可以通过本题。

代码实现

其中含有暴力DP和树状数组优化DP的部分,仅供参考。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;

using LL = long long;

struct Point {
    LL x, y, ny, val;

    Point() {
        x = y = ny = val = 0;
    }
};

bool by_x(Point x, Point y) {
    if (x.x != y.x) {
        return x.x < y.x;
    }
    if (x.y != y.y) {
        return x.y < y.y;
    }
    return x.val < y.val;
}

bool by_y(Point x, Point y) {
    if (x.y != y.y) {
        return x.y < y.y;
    }
    if (x.x != y.x) {
        return x.x < y.x;
    }
    return x.val < y.val;
}

struct BIT {
    LL n;
    vector<LL> t;

    BIT(LL _n) {
        n = _n;
        t.assign(n + 1, 0);
    }

    LL lsb(LL x) {
        return x & (-x);
    }

    LL pre_max(LL i) {
        LL max_val = 0;
        for (LL j = i; j >= 1; j -= lsb(j)) {
            max_val = max(max_val, t[j]);
        }
        return max_val;
    }

    void add(LL i, LL x) {
        for (LL j = i; j <= n; j += lsb(j)) {
            t[j] = max(t[j], x);
        }
    }
};

const LL N = 1e5 + 10;
LL y[N], val[N], dp[N];
Point a[N];
LL n, m, k;

void discretize() {
    sort(a + 1, a + 1 + k, by_y);
    for (LL i = 1; i <= k; i++) {
        if (a[i].y == a[i - 1].y) {
            a[i].ny = a[i - 1].ny;
        } else {
            a[i].ny = a[i - 1].ny + 1;
        }
    }
    for (LL i = 1; i <= k; i++) {
        a[i].y = a[i].ny;
    }
}

void init() {
    sort(a + 1, a + 1 + k, by_x);
    for (LL i = 1; i <= k; i++) {
        y[i] = a[i].y;
        val[i] = a[i].val;
    }
}

void brute_dp() {
    memset(dp, 0, sizeof(dp));
    for (LL i = 1; i <= k; i++) {
        for (LL j = 0; j < i; j++) {
            if (y[j] <= y[i]) {
                dp[i] = max(dp[i], dp[j] + val[i]);
            }
        }
    }
}

void BIT_dp() {
    memset(dp, 0, sizeof(dp));
    BIT tree(k);
    for (LL i = 1; i <= k; i++) {
        dp[i] = tree.pre_max(y[i]) + val[i];
        tree.add(y[i], dp[i]);
    }
}

int main() {
    freopen("travel.in", "r", stdin);
    freopen("travel.out", "w", stdout);

    cin >> n >> m >> k;
    for (LL i = 1; i <= k; i++) {
        cin >> a[i].x >> a[i].y >> a[i].val;
    }
    if (k <= 2000) {
        init();
        brute_dp();
    } else {
        discretize();
        init();
        BIT_dp();
    }
    LL ans = 0;
    for (LL i = 1; i <= k; i++) {
        ans = max(ans, dp[i]);
    }
    cout << ans << endl;

    fclose(stdin);
    fclose(stdout);
}