Move to dormitory 1421

Source: Internet
Author: User
# Include <iostream> # include <algorithm> using namespace STD; # define min (a, B) (a <B? A: B) # define INF 2100000000int DP [2001] [1001]; // The first subscript (2001) indicates int main () {int N; // The number of items int K; // The number of pairs int A [2001]; // array a is first used for the quality of each item, and then used to save the square difference. Int I; // row Int J; // column while (scanf ("% d", & N, & K )! = EOF) {for (I = 1; I <= N; ++ I) {scanf ("% d", & A [I]);} sort (a + 1, A + 1 + n); // sort the numbers from small to large. // calculate the squared difference of the numbers of adjacent pairs for (I = 1; I <N; ++ I) {// place the first squared difference in a [1], and the last one in a [n-1]; A total of N-1 square differences a [I] = (a [I + 1]-A [I]) * (a [I + 1]-A [I]);} /* initialize the DP array */for (I = 0; I <= N; I ++) // 0 rows to N rows for (j = 1; j <= K; j ++) // 1 column to k column DP [I] [J] = inf; // initialize two-dimensional array DP [I] [J] for (I = 0; I <= N; I ++) DP [I] [0] = 0; // The first column is initialized to 0/* formula: DP [I] [J] = min (DP [I-2] [J-1] + A [I-1], DP [I-1] [J]); */For (I = 2; I <= N; ++ I) {// note that I must <= N // select 2 to 3, 4 to J (2 * k <= N) pairs. For (j = 1; 2 * j <= I; ++ J) {// DP [I] [J]: front I take J pair // DP [I-2] [J-1] + A [I-1]: Front I-2 take J-1 pair, finally DP [I] [J] = min (DP [I-2] [J-1] + A [I-1], DP [I-1] [J]); // A [I-1] is the last squared difference // DP [0] [0]} // n total, select K pairs. 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.