[HDU 1421] dormitory migration (innovative DP)

Source: Internet
Author: User

Question address: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1421

N items are given. You need to select K pairs of items to minimize the sum of the squares of each pair of items.

Thinking; Dynamic Planning and solving, first sort items by weight in ascending order. According to greedy ideas, each pair of items must be two adjacent items, so that the square of the weight difference can be minimized. Then, DP uses f [I] [J] to represent the first I item, and selects j pairs at the minimum cost. An important classification discussion is required here:

(1) If J * 2 = I, that is, all the first I items are used for pairing, it is obvious that J is for item No. I-1 and no. I, f [I] [J] = f [I-2] [J-1] + (W [I]-W [I-1]) ^ 2

(2) other cases. The first I items are not completely used for pairing. You can select the I item not to be paired. f [I] [J] = f [I-1] [J], or I items are paired, same as (1), I items are paired with I-1 items, f [I] [J] = f [I-2] [J-1] + (W [I]-W [I-1]) ^ 2

The final answer is f [N] [K].

# Include <iostream> # include <stdio. h> # include <stdlib. h> # include <string. h >#include <algorithm> # define maxn 2010 using namespace STD; int f [maxn] [maxn]; // F [I] [J] = previous I items, select the minimum cost of the J pair int W [maxn]; int min (int A, int B) {if (a <B) return a; return B;} int main () {int N, K; while (scanf ("% d", & N, & K )! = EOF) {memset (F, 0, sizeof (f); W [0] = 0; For (INT I = 1; I <= N; I ++) scanf ("% d", & W [I]); sort (W + 1, W + n + 1); For (INT I = 2; I <= N; I ++) // The first I items for (Int J = 1; j * 2 <= I; j ++) // select the J pair {if (I! = 2 * j) f [I] [J] = min (F [I-2] [J-1] + (W [I]-W [I-1]) * (W [I]-W [I-1]), f [I-1] [J]); // either the I-th item is paired with the I-1-th item, either keep the first item unpaired else f [I] [J] = f [I-2] [J-1] + (W [I]-W [I-1]) * (W [I]-W [I-1]);} printf ("% d \ n", F [N] [k]);} return 0 ;}



Zookeeper

[HDU 1421] dormitory migration (innovative DP)

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.