Move dormitory
Time Limit: 2000/1000 MS (Java/others) memory limit: 65536/32768 K (Java/Others)
Total submission (s): 17775 accepted submission (s): 6031
Problem description it is very tiring to move the bedroom, xhd deep experience. time to record July 9, 2006, xhd was forced to move from building 27 to building 3 that day, because building 10 had to be closed. looking at the N items in the dormitory, xhd started to get in a daze. Because N is an integer smaller than 2000, it is too much. Therefore, xhd decided to move 2 * k items at will. but it will still be very tired, because 2 * K is not small is an integer not greater than N. fortunately, based on years of experience in moving things, xhd finds that the fatigue of each moving is directly proportional to the square of the weight difference between the items in the left and right hands (here, xhd moves two things each time, one on the left and one on the right ). for example, if xhd has an item with a weight of 3 in the left hand and an item with a weight of 6 in the right hand, then the fatigue of the item is (6-3) ^ 2 = 9. now, poor xhd wants to know what the best status (that is, the lowest fatigue) will be after these 2 * k items are moved. Please tell him.
Each input group has two rows. The first row has two numbers, N and K (2 <= 2 * k <= n <2000 ). the second row has n integers representing the weight of N items (weight is a positive integer smaller than 2 ^ 15 ).
Output corresponds to each group of input data, and only one output data indicates its minimum fatigue, each row.
Sample Input
2 11 3
Sample output
4
Idea: Select K heap for N items and directly select K pairs for the first J items by using two-dimensional DP [I] [J.
- J items do not move, that is, in the first J-1 items move K pairs, then the fatigue value is still f [k] [J-1];
- If J items are to be moved, the J-1 items must also be moved at the same time, that is, the K-1 pair of items in the J-2 items are moved in the previous J-2 items, move the last item, then the fatigue value is f [k-1] [J-2] + A [J-1], j-1 is because the logarithm must be 1 less than the total number of items.
Code:
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<cmath>#include<vector>#include<algorithm>#define INF 0x3f3f3f3fusing namespace std;typedef long long LL;int a[2010];int w[2010];int dp[1000][2010];int main(){ int n,k; while(scanf("%d%d",&n,&k)!=EOF) { for(int i=0;i<n;i++) scanf("%d",a+i); sort(a,a+n); for(int i=0;i<n-1;i++) w[i]=(a[i+1]-a[i])*(a[i+1]-a[i]); memset(dp,INF,sizeof dp); for(int i=0;i<n;i++) dp[0][i]=0; for(int i=1;i<=k;i++) { for(int j=2*i-1;j<n;j++) { dp[i][j]=min(dp[i][j-1],dp[i-1][j-2]+w[j-1]); } } printf("%d\n",dp[k][n-1]); } return 0;}
HDU 1421 move dormitory [DP]