Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1421
Given n items, select K pairs. The cost of each pair is the square of the weight difference between the two items. Determine the policy to minimize the total cost.
The restriction of this problem is to take K pairs and the number of items. Therefore, without optimization, we use DP [I] [J] to indicate the minimum cost of selecting the J pair in the previous I see item. Then there is a dynamic transfer equation:
DP [I] [J] = min (DP [I-1] [J], DP [I-2] [J-1] + (W [I]-W [I-1]) * (W [I]-W [I-1]);
The Code is as follows:
# Include <cstdlib> # include <cstring> # include <cstdio> # include <algorithm> # define INF 0x3f3f3fusing namespace STD; int N, K, W [2005], DP [2005] [1005]; void Init () {int limit; For (INT I = 0; I <= N; ++ I) {for (Int J = 0; j <= K; ++ J) {DP [I] [J] = bool (j) * INF; // if this parameter is selected, the value is set to infinity }}} int dp () {int limit; For (INT I = 2; I <= N; ++ I) {Limit = min (I> 1, k); For (Int J = 1; j <= limit; ++ J) {DP [I] [J] = min (DP [I-1] [J], DP [I-2] [J-1] + W [I-1]);} return DP [N] [k];} int main () {While (scanf ("% d", & N, & K) = 2) {for (INT I = 1; I <= N; ++ I) {scanf ("% d", & W [I]) ;} Init (); sort (W + 1, W + 1 + n); For (INT I = 1; I <n; ++ I) {W [I] = (W [I]-W [I + 1]) * (W [I]-W [I + 1]); // cannot be written in the form of W [I]-W [I-1, because this will overwrite part of the Information // define W [I] For I good element and I-1 number element difference} printf ("% d \ n", dp ());} return 0 ;}