HDU 1421 DP Entry question

Source: Internet
Author: User
Tags min

http://acm.hdu.edu.cn/showproblem.php?pid=1421

Chinese questions

Idea: First to find out how to combine all the items into a pair of, the problem requires the smallest fatigue, that is, a pair of two items in the weight of the smallest difference. Then you need to use the sorting, the items from small to large, from traversing the items until the second to the last, each item and the next item is combined into a pair, it will be found that if we first selected this pair, then the next pair can not be selected, because one of the elements is duplicated.

Probably clear the idea after the discovery state definition does not come out ... I don't know how to make sure he is k ... DP really need to slowly, slowly cultivate their own feeling it.

Define state: Dp[i][j] means to select the J pair from the I item

In two cases, one is to not select the current pair dp[i][j] = Dp[i-1][j], one is to select the current pair dp[i][j] = Dp[i-2][j-1]+a[i-1]

State transition equation: dp[i][j] = min (dp[i-1][j],dp[i-2][j-1]+a[i-1])

Code:

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace
Std
#define M #define INF 0x3f3f3f3f int a[m]; int dp[m][m];
    DP[I][J] indicates that a J pair is selected from the I item to int main () {int n,k;
        while (scanf ("%d%d", &n,&k) ==2) {for (int i = 1;i <= n;i++) scanf ("%d", &a[i]); Sort (a+1,a+n+1);//small to large rows make the gap minimum for (int i = 1;i <= n-1;i++) a[i] = (a[i]-a[i+1]) * (a[i]-a[i+1]); Calculates the fatigue for each pair (int i = 1;i <= n;i++) for (int j = 0;j <= n;j++) {Dp[i][j] = in   F  Because it is to find the minimum value, it is assigned an initial of INF} for (int i = 1;i <= n;i++) {dp[i][0] = 0; If you choose 0 pairs from I, the fatigue value must be 0 for (int j = 0;2*j <= i;j++) {if (i==1) dp[i][j] = Dp[i-1][j ];
            Special Case Else Dp[i][j] = min (dp[i-1][j],dp[i-2][j-1]+a[i-1]);
    }} printf ("%d\n", Dp[n][k]);
} return 0;
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.