Simple Dynamic Programming E- move bedroom (winter training)

Subject of the request
to move the bedroom is very tired, xhd deep. Time traced July 9, 2006, the day xhd forced to move from Building 27, Building 3, as No. 10 to seal the floor. Looked at the bedroom where n items, xhd start in a daze, because n is an integer less than 2000, it is too much, so he decided to just move xhd 2 k pieces of the past on the line, but still very tired, because 2 is not small k is n is an integer greater than Fortunately XHD each time it is found that fatigue is proportional to the square of the difference in weight of the right hand of the article (add here that, each transfer two things XHD based on years of experience of moving things, a left hand one). For example the left hand xhd weight of the article 3, the right hand of the weight of the article 6, the degree of his fatigue of the move those (6-3) ^ 2 = 9. now poor xhd this move those 2 would like to know the best condition after what k items (that is, the lowest fatigue), please tell him.
the input
input data in each group there are two lines, the first line there are two numbers n, k (2 <2 =
K <= n <2000). the second row has n each represent an integer of n items by weight (weight being a positive integer smaller than 2 ^ 15).
the Output
corresponding to each input Data, the output data represents only a minimum of his fatigue, each row.
The Sample the Input
2. 1
. 1. 3
the Sample the Output
. 4
required throughout the process of fatigue minimum, the first array value dp assigned to a maximum value, are arranged in an array each value, in order to take the adjacent article. DP [i] [j] denotes the front i j items selected minimum fatigue article obtained, the dynamic transition equationdp[i][j] = min(dp[i - 1][j], dp[i - 2][j - 1] + (a[i] - a[i - 1]) * (a[i] - a[i - 1]));

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[2010][2010], a[2010];
#define maxn 0x3f3f3f3f
int main()
{
    int n, k;
    while (~scanf("%d%d", &n, &k))
    {
        int i, j;
        memset(a, 0, sizeof(a));
        memset(dp, 0, sizeof(dp));
        for (i = 0; i <= n; i++)
            for (j = 1; j <= k; j++)
                dp[i][j] = maxn;
        for (i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        sort(a, a + n + 1);
        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] + (a[i] - a[i - 1]) * (a[i] - a[i - 1]));
        printf("%d\n", dp[n][k]);
    }
    return 0;
}
Published 38 original articles · won praise 27 · views 3166

Guess you like

Origin blog.csdn.net/qq_45891413/article/details/105281022