Remember to do a classic topic, is also selected K sets of chopsticks, then not difficult to describe the state, that is, with D[i][j] in the first I root chopsticks in the choice of J-double the optimal solution, the only difference is to add a long chopsticks, in order to solve this problem, we must find ways to exclude the longest chopsticks in the state of the impact.
Let's consider the simple situation first, assuming that there is no longest chopsticks, then there are only two decisions for each state: the first and second chopsticks are selected. Because it is already lined up, it is best to choose two adjacent chopsticks, so if you do not select root I, the state is transferred from D[i-1][j], and if you choose root I, the state is transferred from D[i-2][j-1] + (a[i]-a[i-1]) ^2. It is well understood that the crux of the problem is to solve the effects of the longest chopsticks!
If we choose according to the order from small to large, there will be a problem, the choice of the first I chopsticks as the first set of tableware, which chopsticks to choose as the longest in the first set of J? Obviously, the state is disorderly, difficult to transfer, because the long chopsticks are in the back, you can not predict which long chopsticks have been selected. So we have to choose from the big to the small, and so on, this is not enough, do not forget, we have to choose a chopstick as the longest, so add a restriction on the line: I >= j*3.
Careful readers should have found that the problem of J can only be transferred from the j-1, like a backpack, the problem can also be solved with a rolling array, D[j] indicates the current state of the optimal solution of the J set of chopsticks.
See the code for details:
#include <bits/stdc++.h>using namespace Std;typedef long Long ll;const ll INF = 100000000000000; Open ll just be careful, the problem does not open Llint t,k,n,a[5000 + 10];ll d[5000 + 10][1000 + 10];int main () { scanf ("%d", &t); while (t--) { scanf ("%d%d", &k,&n); K + = 8; for (int i=n;i>=1;i--) scanf ("%d", &a[i]); From large to small, in order to eliminate the effect of the longest chopsticks, so for each set of chopsticks will have the longest chopsticks. for (int i=0;i<=n;i++) for (int j=0;j<=k;j++) D[i][j] = (j = = 0? 0:inf);//Initialize boundary. for (int i=3;i<=n;i++) {for (int j=1;j<=k;j++) { if (I >= j*3)//Because there is the limit of the longest chopsticks, so that the effect can be ignored, Because there must be enough of the longest chopsticks. D[i][j] = min (d[i-1][j],d[i-2][j-1]+ (a[i]-a[i-1]) * (A[i]-a[i-1]); } For the I-root chopsticks do not take or take } printf ("%lld\n", D[n][k]); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
10271-chopsticks (DP)