题目链接
思路
如果选择机器人当前所在的点和当前的载重作为状态的话,其中n <= 100000, C<= 100,则状态数一共就有1e7,明显会T,于是只有减少状态数。
考虑仅将当前所在的点i作为状态,则为了避免当前载重的影响,设定状态d[i]为从原点出发, 已经将前i个垃圾放进垃圾桶所走的最短距离。则转移方程为:
d[i] = min{d[j] + dist2origin(j + 1) + dist(j + 1, i) + dist2origin(i) | j <= i && w(j + 1, i) <= C}
其中dist2origin(i)为当前点i到原点的距离,dist(j + 1, i)为从j + 1开始,依次经过j + 1, j + 2, i所走过的距离
其中dist可以用前缀和来维护,设tot_dist(i)为从原点开始依次经过1, 2,一直到i所走过的全部距离,则dist(j + 1, i)可表示为tot_dist(i) - tot_dist(j + 1)
则上面的式子就可以写成
d[i] = min{d[j] + dist2origin(j + 1) + tot_dist(i) - tot_dist(j + 1) + dist2origin(i)| j <= i && w(j + 1, i) <= C)
再设func[j] = d[j] - tot_dist(j + 1) + dist2origin(j + 1)
那么上面的式子就可以写做:
d[i] = min{func[j]} + tot_dist(i) + dist2origin(i) | j <= i && w[j + 1, i] <= C}
因为w[j + 1, i] <= C对应的是一个区间,于是像窗口滑动问题,只需要维护滑动区间最小值,参考POJ2823,用一个单调队列来维护滑动窗口的最小值,时间复杂度O(n)
代码
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;
#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
const int maxn = 100000 + 5;
int tot_dist[maxn], tot_weight[maxn], dist2origin[maxn], x[maxn], y[maxn];
int d[maxn], n, C;
int func(int j) {
return d[j] + dist2origin[j + 1] - tot_dist[j + 1];
}
int main() {
int T, _w;
scan(T);
while (T--) {
scan(C);
scan(n);
tot_dist[0] = tot_weight[0] = x[0] = y[0] = 0;
for (int i = 1; i <= n; i++) {
scan3(x[i], y[i], _w);
tot_weight[i] = tot_weight[i - 1] + _w;
tot_dist[i] = tot_dist[i - 1] + (fabs(x[i] - x[i - 1]) + fabs(y[i] - y[i - 1]));
dist2origin[i] = fabs(x[i]) + fabs(y[i]);
}
deque<int> q;
q.push_front(0);
for (int i = 1; i <= n; i++) {
while (!q.empty() && tot_weight[i] - tot_weight[q.front()] > C) q.pop_front();
d[i] = func(q.front()) + tot_dist[i] + dist2origin[i];
while (!q.empty() && func(i) <= func(q.back())) q.pop_back();
q.push_back(i);
}
printf("%d\n", d[n]);
if (T > 0) pl();
}
return 0;
}