中等DP,开始想了半天没想出来,我思路一直是从前向后递推的,感觉这样有问题,还好没有直接写,不然肯定WA死,网上搜了搜受到启发,如果从后往前递推的话就解决问题了,用滚动数组优化了下空间
#include<stdio.h>
#include<string.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
#define BAD(a,b) ((a-b)*(a-b))
int main()
{
int T, K, N, a[5000], dp[2][5000];
scanf("%d", &T);
while (T--)
{
scanf("%d %d", &K, &N);
int i, k;
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
memset(dp[0], 0, sizeof(dp[0]));
int now, end;
for (k = 1; k <= K + 8; k++)
{
end = N - k * 3;
now = k & 1;
dp[now][end] = BAD(a[end], a[end + 1]) + dp[!now][end + 2];
for (i = end - 1; i >= 0; i--)
dp[now][i] = MIN(dp[now][i + 1],
BAD(a[i], a[i + 1]) + dp[!now][i + 2]);
}
printf("%d\n", dp[now][0]);
}
return 0;
}