http://acm.hdu.edu.cn/showproblem.php?pid=1421
状态:
dp[i][j] 表示i件物品搬j组
转移方程:
dp[i][j] = Min( dp[i-2][j-1] + qwe(w[i] - w[i-1]),dp[i-1][j] );
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<functional>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 2005;
const int inf = 1<<30;//0x7f;
typedef __int64 LL;
int n,K;
int dp[maxn][maxn],w[maxn];
void GetDp()
{
for( int i = 0; i <= n; i ++ )
for( int j = 1; j <= K; j ++ )
dp[i][j] = inf;
for( int i = 2; i <= n; i ++ ){
for( int j = 1; j <= K; j ++ )
{
dp[i][j] = min( dp[i-1][j],dp[i-2][j-1] + ( w[i]-w[i-1] )*( w[i]-w[i-1] ));
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("data.txt","r",stdin);
#endif
char str[maxn],p[maxn];
while( scanf("%d%d",&n,&K) != EOF )
{
for( int i = 1; i <= n; i ++ )
scanf("%d",&w[i]);
sort( w+1,w+n+1 );
GetDp();
printf("%d\n",dp[n][K]);
}
return 0;
}
滚动数组:
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<functional>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 2005;
const int inf = 1<<30;//0x7f;
typedef __int64 LL;
int n,K;
int dp[4][maxn>>1],w[maxn];
void GetDp()
{
for( int i = 1; i <= K; i ++ )
dp[0][i] = dp[1][i] = inf;
for( int i = 2; i <= n; i ++ ){
for( int j = 1; j <= K; j ++ ){
dp[i%3][j] = min( dp[(i-1)%3][j],dp[(i-2)%3][j-1] + ( w[i]-w[i-1] )*( w[i]-w[i-1] ));
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("data.txt","r",stdin);
#endif
char str[maxn],p[maxn];
while( scanf("%d%d",&n,&K) != EOF )
{
for( int i = 1; i <= n; i ++ )
scanf("%d",&w[i]);
sort( w+1,w+n+1 );
GetDp();
printf("%d\n",dp[n%3][K]);
}
return 0;
}