Hdu 1421 to move the bedroom

Hdu 1421 conveyed bedroom (dp)

Topic links: http://acm.hdu.edu.cn/showproblem.php?pid=1421
Here Insert Picture Description
problem-solving ideas:
For each item, there are two approaches to take and not take, if you took, it would have to plus fatigue value, does not take, it is equal to the front quite good results, (initialization to complete), treated with a two-dimensional dp, i represents the number of items, j represents a number of items, the state transition equation: DP [I] J = min (DP [I-. 1] J , DP [I-2] [J-. 1] + (NUM [I] - NUM [I -. 1]) * (NUM [I] - NUM [I -. 1]) (in the case, then taken to reduce the equivalent number of articles 2 to obtain fatigue value plus two articles produced)).
code show as below:

#include <bits/stdc++.h>

#define inf 0x3f3f3f
#define MAXN 2005
int dp[MAXN][MAXN], num[MAXN];

inline int min(int a, int b) {//取小
    return a > b ? b : a;
}

int main() {
    int n, k;
    while (scanf("%d %d", &n, &k) != EOF) {
        memset(dp, inf, sizeof(dp));
        dp[0][0] = 0;//i为0是第一次dp跑的位置,不能忘记清0
        for (int i = 1; i <= n; i++) {
            scanf("%d", &num[i]);
            dp[i][0] = 0;
        }
        std::sort(num + 1, num + n + 1);//排序保证相邻最小
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i / 2; j++) {
                dp[i][j] = min(dp[i - 1][j], dp[i - 2][j - 1] + (num[i] - num[i - 1]) * (num[i] - num[i - 1]));//取两种方案的最小值
            }
        }
        printf("%d\n", dp[n][k]);
    }
    return 0;
}
Published 35 original articles · won praise 3 · Views 879

Guess you like

Origin blog.csdn.net/weixin_43823753/article/details/104716930