题意:给出一个序列,首尾不可改变,要求你使序列满足相邻2个|x_i - x_(i-1)| <=d,改变的代价就是两数相减绝对值,问最小代价。
做法:通过枚举可以发觉每个数字只能变成a_i+k*d这种形式的数字,那么这样每个数的状态只有n^2个了,不过转移的话代价比较高,因为对于d(i,x)需要枚举d(i-1,y)| x - d <= y <= x+d最小的转移过来,其实这个就是相当于一个求区间最值的问题,我们可以利用单调队列做到线性的,下标递增,值也是递增的,如果当前值要大于队首,那么直接加上,反之就要把那些大于当前值的元素出队列,因为我当前要求的区间右边界已经到这里了,意味着最小值至少是当前这个了,比他大的自然就没用了。这是左边界的处理,右边界的话,就看是否满足x-d<=y即可。不满足就让队尾的出队,直至满足为止。
AC代码:
//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdlib>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<string.h>
#include<string>
#include<sstream>
#include<bitset>
using namespace std;
#define ll long long
#define ull unsigned long long
#define eps 1e-8
#define MOD 1000000007
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1)
#define NMAX (ll)1<<50
template<class T>
inline void scan_d(T &ret)
{
char c;
int flag = 0;
ret=0;
while(((c=getchar())<'0'||c>'9')&&c!='-');
if(c == '-')
{
flag = 1;
c = getchar();
}
while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
if(flag) ret = -ret;
}
template<class T> inline T Max(T a, T b){ return a > b ? a : b; }
template<class T> inline T Min(T a, T b){ return a < b ? a : b; }
ll a[105],b[20000+200];
ll dp[105][20000+200];
ll que[20000+200][2];
int nct;
int getpos(int x)
{
return lower_bound(b,b+nct,x)-b;
}
ll cal(ll a, ll b)
{
ll ret = a-b;
if(ret < 0) ret = -ret;
return ret;
}
int main()
{
#ifdef GLQ
freopen("input.txt","r",stdin);
// freopen("o1.txt","w",stdout);
#endif // GLQ
int cas,n;
ll d;
scanf("%d",&cas);
while(cas--)
{
scanf("%d%lld",&n,&d);
for(int i = 0; i < n; i++)
scanf("%lld",&a[i]);
nct = 0;
for(int i = 0; i < n; i++)
{
b[nct++] = a[i];
for(int j = 1; j < n; j++)
{
b[nct++] = a[i]+(ll)j*d;
if(a[i]-(ll)j*d >= 0) b[nct++] = a[i]-(ll)j*d;
}
}
sort(b,b+nct);
nct = unique(b,b+nct)-b;
for(int i = 0; i < n; i++)
for(int j = 0; j < nct; j++)
dp[i][j] = NMAX;
dp[0][getpos(a[0])] = 0;
int front,rear;
for(int i = 0; i < n-1; i++)
{
front = -1; rear = 0;
int k = 0;
for(int j = 0; j < nct; j++)
{
while(k < nct && cal(b[k],b[j]) <= d)
{
if(front >= rear && dp[i][k] <= que[front][1])
{
while(front >= rear && dp[i][k] <= que[front][1])
front--;
}
que[++front][0] = k;
que[front][1] = dp[i][k];
k++;
}
while(cal(b[que[rear][0]],b[j]) > d) rear++;
dp[i+1][j] = Min(dp[i+1][j],que[rear][1]+cal(a[i+1],b[j]));
}
}
if(dp[n-1][getpos(a[n-1])] == NMAX) printf("impossible\n");
else printf("%lld\n",dp[n-1][getpos(a[n-1])]);
}
return 0;
}