题意:有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) #define sfi2(n, m) scanf("%d%d", &n, &m) #define pfi2(n, m) printf("%d %d ", n, m) #define pfi3(a, b, c) printf("%d %d %d ", 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 += 9, n++; for(int i = n - 1; i >= 1; i--) sfi(L[i]); repu(i, 0, n) { dp[i][0] = 0; repu(j, 1, k) dp[i][j] = INF; } repu(i, 3, n) { int t = i / 3 + 1; t = min(t, k); repu(j, 1, t) { dp[i][j] = min(dp[i - 1][j], dp[i - 2][j - 1] + (L[i] - L[i - 1]) * (L[i] - L[i - 1])); } } pfi(dp[n - 1][k - 1]); } return 0; }