Title: In n number, find K ternary group (A<=B<=C), the smallest (a-B) * (A-B) sum.
Title Analysis: To sort all the numbers from large to small, define DP (I,J) to indicate the minimum and maximum number of J triples found in the first I, then the state transition equation is DP (I,J) =min (DP (I-1,J), DP (I-2,J-1)), The second decision is to be made on the premise that the first i-1 number constitutes the J-1 group and must have the remaining number. The problem is similar to "moving a bedroom" and "chopsticks", and the same should be solved by filling in the form and paying attention to borders.
The code is as follows:
# include<iostream># include<cstdio># include<cstring># include<algorithm>using namespace std;# define LL long longconst int inf=1<<30;int m,n,a[5005];int dp[5005][1010];int Solve () { m+=8; for (int i=0;i<n;++i) { dp[i][0]=0; for (int j=1;j<=m;++j) dp[i][j]=inf; } for (int i=2;i<n;++i) {for (int j=1;j<=m;++j) if (i>=3*j-1) dp[i][j]=min (dp[i-1][j],dp[i-2][j-1]+ (A [I]-a[i-1]) * (a[i]-a[i-1])); } return dp[n-1][m];} int main () { int T; scanf ("%d", &t); while (t--) { scanf ("%d%d", &m,&n); for (int i=n-1;i>=0;--i) scanf ("%d", a+i); printf ("%d\n", Solve ()); } return 0;}
UVA-10271 chopsticks (linear DP)