2026/07/03 模拟赛 B
stephen_yin · · 题解
旅行 / Travel
题意简述
在一个
题目分析
首先考虑最短路径的含义。即所涉及到的点满足二维偏序。
暴力DP
考虑朴素DP:
- 首先按照
x_i 排序,消除一维偏序,即i < j 时,x_i < x_j 。 -
-
上述算法时间复杂度
树状数组优化DP
考虑优化:
- 观察上述DP转移方程式,考虑用一个点的
y 值代表这个点。 - 则每次转移转化为查询前缀最大值。
- 每次再将计算出的DP值单点修改。
- 于是我们需要一个数据结构,支持快速的单点修改和查询前缀最大值。
- 使用树状数组可以高效维护。
- 回到上面,使用
y 值代表一个点,然而y_i \le 10^9 。 - 使用离散化缩小
y 的值域。
上述算法时间复杂度
代码实现
其中含有暴力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);
}