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;
}