分析:dp[i][j]表示前i个元素中 j 对数的最小差平方和
dp[i][j] = min(dp[i-1][j], dp[i-2][j-1] + (weight[i] - weight[i-1])*(weight[i] - weight[i-1]));
code:
#include<stdio.h>
#include<stdlib.h>
#define min(a,b) ((a) > (b) ? (b) : (a))
#define MaxAllow 2147483648
const int num = 2001;
int cmp(const void* a, const void *b)
{
return *(int*)a - *(int*)b;
}
int dp[num][1001]; //数组要在函数外定义,不然太大不行,无语,又卡了n久
int main()
{
int n, k;
int i, j;
int weight[num];
while(scanf("%d%d", &n, &k) != EOF)
{
for(i = 1; i <= n; i++)
scanf("%d", &weight[i]);
for(i = 0; i <= n; i++)
for(j = 1; j <= k; j++)
dp[i][j] = MaxAllow;
dp[0][0] = 0;
for(i = 2; i <= n; i++)
for(j = 1; j*2 <= i; j++)
{
dp[i][j] = min(dp[i-1][j],dp[i-2][j-1]+(weight[i]-weight[i-1])*(weight[i] - weight[i-1]));
}
printf("%d\n", dp[n][k]);
}
return 0;
}