原题链接:https://vjudge.net/problem/UVA-12170
分类:动态规划
备注:思维,单调队列
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 200 + 5;
const LL INF = 1e18;
int t, n, d;
LL h[N], x[N * N * 2 + 5], f[N][2 * N * N];
struct Node {
LL y, f;
};
bool check(LL xl, LL xr, LL yl, LL yr) {
if (xr < yl) return false;
if (yr < xl) return false;
return true;
}
int main(void) {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &d);
for (int i = 1; i <= n; i++)
scanf("%lld", &h[i]);
if (n == 2) {
if (abs(h[1] - h[2]) > d) puts("impossible");
else puts("0");
continue;
}
int tot = 0;
for (int i = 1; i <= n; i++)
for (int j = 1 - n; j < n; j++)
x[++tot] = h[i] + 1LL * j * d;
sort(x + 1, x + 1 + tot);
for (int i = 2; i < n; i++)
for (int j = 1; j <= tot; j++)
f[i][j] = INF;
for (int i = 1; i <= tot; i++) {
if (x[i] > h[1] + d) break;
if (x[i] >= h[1] - d)
f[2][i] = abs(h[2] - x[i]);
}
for (int i = 3; i < n; i++) {
int pos = 1;
deque<Node>dq;
for (int j = 1; j <= tot; j++) {
while (!dq.empty() && dq.front().y < x[j] - d) dq.pop_front();
while (pos <= tot && x[pos] <= x[j] + d) {
LL fval = f[i - 1][pos];
if (fval != INF) {
while (!dq.empty() && dq.back().f > fval) dq.pop_back();
dq.push_back(Node{x[pos], fval});
}
pos++;
}
if (!dq.empty())
f[i][j] = abs(h[i] - x[j]) + dq.front().f;
}
}
LL ans = INF;
for (int i = 1; i <= tot; i++) {
if (x[i] > h[n] + d) break;
if (x[i] >= h[n] - d) ans = min(ans, f[n - 1][i]);
}
if (ans == INF) puts("impossible");
else printf("%lld\n", ans);
}
return 0;
}