hdu 1500 Chopsticks DP

题目链接:HDU - 1500

In China, people use a pair of chopsticks to get food on the table, but Mr. L is a bit different. He uses a set of three chopsticks -- one pair, plus an EXTRA long chopstick to get some big food by piercing it through the food. As you may guess, the length of the two shorter chopsticks should be as close as possible, but the length of the extra one is not important, as long as it's the longest. To make things clearer, for the set of chopsticks with lengths A,B,C(A<=B<=C), (A-B)^2 is called the 'badness' of the set.
It's December 2nd, Mr.L's birthday! He invited K people to join his birthday party, and would like to introduce his way of using chopsticks. So, he should prepare K+8 sets of chopsticks(for himself, his wife, his little son, little daughter, his mother, father, mother-in-law, father-in-law, and K other guests). But Mr.L suddenly discovered that his chopsticks are of quite different lengths! He should find a way of composing the K+8 sets, so that the total badness of all the sets is minimized.
Input
The first line in the input contains a single integer T, indicating the number of test cases(1<=T<=20). Each test case begins with two integers K, N(0<=K<=1000, 3K+24<=N<=5000), the number of guests and the number of chopsticks. There are N positive integers Li on the next line in non-decreasing order indicating the lengths of the chopsticks.(1<=Li<=32000).
Output
For each test case in the input, print a line containing the minimal total badness of all the sets.
题意描述:有K+8个人,每个人用3根筷子,现在有n根筷子,知道每根筷子的长度,要求给这些人分配一些筷子,使得每个人短的那两根筷子的差值平方总和最小。
算法分析:对筷子长度从大到小排序,dp[i][j]表示前i个人j根筷子的最优解。
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<cmath>
 6 #include<algorithm>
 7 #define inf 0x7fffffff
 8 using namespace std;
 9 const int maxn=5000+10;
10 
11 int k,n,num[maxn];
12 int dp[1000+10][maxn];
13 
14 int main()
15 {
16     int t;
17     scanf("%d",&t);
18     while (t--)
19     {
20         scanf("%d%d",&k,&n);
21         for (int i=n ;i>=1 ;i--) scanf("%d",&num[i]);
22         k += 8;
23         memset(dp,0,sizeof(dp));
24         for (int i=1 ;i<=k ;i++)
25         {
26             dp[i][3*i]=dp[i-1][3*i-2]+(num[3*i-1]-num[3*i])*(num[3*i-1]-num[3*i]);
27             for (int j=3*i+1 ;j<=n ;j++)
28                 dp[i][j]=min(dp[i][j-1],dp[i-1][j-2]+(num[j-1]-num[j])*(num[j-1]-num[j]));
29         }
30         printf("%d\n",dp[k][n]);
31     }
32     return 0;
33 }

 

posted @ 2015-04-18 01:48  huangxf  阅读(400)  评论(0编辑  收藏  举报