uva 10271 (dp)

时间:2023-11-10 17:30:14

题意:有n个数据,给定k,要从中选出k+8个三元组(x,y,z,其中x<=y<=z),每选一次的代价为(x-y)^2,求最小代价和。

[解题方法]
将筷子按长度从大到小排序
排序原因:
由于一组中A<=B<=C
选第i根筷子作为A时,必然要选第i-1根作为B,否则不会达到最优
dp[i][j]表示选了对于前j根筷子选了i个筷子集合时的最小花费
设c[j]为选j作为A,j-1作为B时的花费(c[j]=(w[i]-w[i-1])^2;),状态转移如下:
dp[i][j] = min( dp[i-1][j-2]+c[j](j>=3*i), dp[i][j-1](j>=3*i+1) );
要j和j-1作为AB形成新的筷子组 不要j作为A形成新筷子组
由于还有C,C>=B>=A,所以j被限制了范围,所以对于dp[i][j]:
形成i个筷子组中最后一组的A最低只能在3*i形成,所以确定了j的范围

#include <cstdio>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
#define ll long long
#define _cle(m, a) memset(m, a, sizeof(m))
#define repu(i, a, b) for(int i = a; i < b; i++)
#define repd(i, a, b) for(int i = b; i >= a; i--)
#define sfi(n) scanf("%d", &n)
#define pfi(n) printf("%d\n", n)
#define sfi2(n, m) scanf("%d%d", &n, &m)
#define pfi2(n, m) printf("%d %d\n", n, m)
#define pfi3(a, b, c) printf("%d %d %d\n", a, b, c)
#define MAXN 1005
#define MAXM 5005
const int INF = 0x3f3f3f3f;
int dp[MAXM][MAXN];
int L[MAXM]; int main()
{
int n, T, k;
sfi(T);
while(T--)
{
sfi2(k, n);
k += , n++;
for(int i = n - ; i >= ; i--) sfi(L[i]);
repu(i, , n)
{
dp[i][] = ;
repu(j, , k) dp[i][j] = INF;
}
repu(i, , n)
{
int t = i / + ;
t = min(t, k);
repu(j, , t)
{
dp[i][j] = min(dp[i - ][j],
dp[i - ][j - ] + (L[i] - L[i - ]) * (L[i] - L[i - ]));
}
}
pfi(dp[n - ][k - ]);
}
return ;
}