1题目:
1 #include<iostream> 2 #include<stdio.h> 3 #include<algorithm> 4 using namespace std; 5 #define M 999999999 6 7 int dp[2000][2000]; 8 9 int getmin(int x, int y){ 10 return x > y ? y : x; 11 } 12 13 int main(){ 14 int n, k, i, j, a[2001], smax[2000], num; 15 while(scanf("%d %d", &n, &k) != EOF){ 16 num = 0; 17 for(i = 1; i <= n; i ++){ 18 scanf("%d", &a[i]); 19 } 20 sort(a, a + n + 1); 21 //cout<<a[1]<<a[2]; 22 for(i = 1; i < n; i ++){ 23 smax[i] = (a[i] - a[i + 1]) * (a[i] - a[i + 1]); 24 } 25 for(i = 0; i <= n; i ++){ 26 for(j = 0; j <= k; j ++){ 27 dp[i][j] = M; 28 } 29 } 30 for(i = 0; i <= n; i ++){ 31 dp[i][0] = 0; 32 } 33 //核心代码 34 for(i = 2; i <= n; i ++){ 35 for(j = 1; 2 * j <= i; j ++){ 36 dp[i][j] = getmin(smax[i - 1] + dp[i - 2][j - 1], dp[i - 1][j]); 37 } 38 } 39 cout << dp[n][k] << endl; 40 } 41 return 0; 42 }