按照紫书的动态规划的思想,首先是保存所有的可能使用的台阶的高度,然后依次“修改”每一级的台阶,将所有结果都进行保存,作为下一级台阶修改的基础,最后查找输出最终的结果,注意INF的初始化要写成(1LL<<60),在这个点上卡了好久,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
typedef long long LL;
LL Case;
LL n, d;
LL h[110];
LL number[105*105*2];
LL dp[2][105*105*2];
LL INF = (1LL << 60);
int main(){
cin >> Case;
while (Case--){
cin >> n >> d;
for (LL i = 0; i < n; i++) cin >> h[i];
if (abs(h[n - 1] - h[0])>(n - 1)*d){
cout << "impossible\n";
continue;
}
LL amount = 0;
for (LL i = 0; i < n; i++){
for (LL k = -(n - 1); k <= n - 1; k++){
number[amount++] = h[i] + k*d;
}
}
sort(number,number+amount);
amount = unique(number, number + amount) - number;
int ind = 0;
for (int j = 0; j < amount;j++){
dp[ind][j] = INF;
if (number[j] == h[0]) dp[ind][j] = 0;
}
for (LL i = 1; i < n; i++){
LL k = 0;
for (LL j = 0; j < amount; j++){
while (k < amount&&number[k] < number[j] - d) k++;
while (k + 1 < amount&&number[k + 1] <= number[j] + d&&dp[ind][k+1]<=dp[ind][k]) k++;
if (dp[ind][k] == INF) dp[ind ^ 1][j] = INF;
else dp[ind ^ 1][j] = dp[ind][k] + abs(h[i]-number[j]);
}
ind = ind ^ 1;
}
for (int i = 0; i < amount; i++){
if (number[i] == h[n - 1]){
cout << dp[ind][i] << endl;
break;
}
}
}
return 0;
}