Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1421
Analysis: to minimize the sum of squares of the difference, the two pieces obtained at a time must be the two that are placed together after sorting. Therefore, the array is first sorted. if I = 2 * j, select all. If I add a number (I + 1), select either of the two conditions. that is: DP [I] [J] = min (DP [I-1] [J], DP [I-2] [J-1] + C ); C = (F [I]-f [I-1]) ^ 2;
That is to say, if selected, then the last pair must be f [I] and f [I-1], then the number of people in the front of the I-2 to select the J-1.
In addition, because I in the outer loop and each time only to the continuous I-2, I-1, I three, so you can turn the front don't need to fold,DP [I % 3] [J] = min (DP [(I-1) % 3] [J], DP [(I-2) % 3] [J-1] + C );
# Include <iostream> # include <string> # include <cstring> # include <algorithm> # include <cstdio> # include <cmath> using namespace STD; const int maxn = 2000 + 10; const int INF = 10000000; int f [maxn]; int DP [3] [maxn]; int main () {int N, K; while (CIN> N> K) {for (INT I = 1; I <= N; ++ I) CIN> F [I]; sort (F + 1, F + n + 1); memset (DP, 0, sizeof (DP); For (INT I = 2; I <= N; ++ I) {for (Int J = 1; j <= K & J * 2 <= I; ++ J) {int c = (F [I-1]-f [I]) * (F [I-1]-f [I]); If (J * 2 = I) DP [I % 3] [J] = DP [(I-2) % 3] [J-1] + C; else DP [I % 3] [J] = min (DP [(I-1) % 3] [J], DP [(I-2) % 3] [J-1] + C); }}cout <DP [n % 3] [k] <Endl ;}return 0 ;}