Address: https://www.acwing.com/problem/content/284/
Topic: Give a pile of stones, adjacent mergers, ask the minimum cost, the specific algorithm is in the question.
Resolution:
For this question, according to common sense, for the final state, the two groups merged. So define dp [i] [j] to represent the minimum value of the interval ij merger.
Two piles merge: dp [1] [2] = dp [1] [1] + dp [2] [2] + sum [1 ~ 2];
即dp[i][i+1]=dp[i][i]+dp[i+1][i+1]+sum[i~i+1];
Three piles combined: dp [1] [3] = min (dp [1] [1] + dp [2] [3], dp [1] [2] + dp [3] [3]) + sum [1 ~ 3];
dp[i][i+2]=min(dp[i][i]+dp[i+1][i+2],dp[i][i+1]+dp[i+2][i+2])+sum[i~i+2];
In summary, it is extended to the merge of the i-th pile to the j-th pile, dp [i] [j] = min (dp [i] [j], dp [i] [k] + dp [k + 1] [j] + sum [j] -sum [i-1]);
Three fors is equivalent to traversing each length interval.
It feels a bit floyed ... Find a transit point
#include<iostream> #include<cstdio> #include<cstring> const int maxn = 500; const int inf = 1e9; int dp[maxn][maxn]; int a[maxn],sum[maxn]; using namespace std; int main() { int n; cin>>n; sum[0]=0; for(int i = 1;i <= n ; i++) { cin>>a[i]; sum[i]=sum[i-1]+a[i]; } for(int len =2 ; len <= n ;len++) { for(int l = 1; l+len-1<=n; l++) { int r=l+len-1; dp[l][r]=inf; for(int k = l ; k < r ; k ++) { dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r]+sum[r]-sum[l-1]); } } } cout<<dp[1][n]<<endl; }