题目链接 :http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=737
这个动态规划的思是,要得出合并n堆石子的最优答案可以从小到大枚举所有石子合并的最优情况,例如要合并5堆石子就可以从,最优的2+3和1+4中得到最佳的答案。从两堆最优到三堆最优一直到n堆最优。
状态转移方程式:dp [ i ] [ j ] = min(dp [ i ] [ k ] + dp [ k+1 ] [ j ])
复杂度为o(n^3)
#include<bits/stdc++.h>
using namespace std;
const int maxn = 210;
int dp[maxn][maxn],sum[maxn];
int main()
{int n;while(scanf("%d",&n) != EOF){memset(dp,0,sizeof(dp));for(int i=1;i<=n;i++){int now;scanf("%d",&now);sum[i] = sum[i-1] + now;}for(int l=2;l<=n;l++)//从i开始长度为l合并的最优答案for(int i=1;i<=n-l+1;i++){int j = i + l - 1;dp[i][j] = 0x7f7f7f7f;for(int k=i;k<=j;k++)dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1]);}printf("%d\n",dp[1][n]);}return 0;
}
经过平行四边形优化之后复杂度为o(n^2)
平行四边形优化https://baike.baidu.com/item/%E5%9B%9B%E8%BE%B9%E5%BD%A2%E4%B8%8D%E7%AD%89%E5%BC%8F?fr=aladdin
/*由平行四边形原理可得,s[i-1][j]<=s[i][j]<=s[i+1][j]*/
#include<bits/stdc++.h>
using namespace std;
const int maxn = 210;
int dp[maxn][maxn],sum[maxn],s[maxn][maxn];void init(int n)
{memset(dp,0,sizeof(dp));memset(s,0,sizeof(s));for(int i=1;i<=n;i++){int now;scanf("%d",&now);s[i][i] = i;sum[i] = sum[i-1] + now;}
}int main()
{int n;while(scanf("%d",&n) != EOF){init(n);for(int l=2;l<=n;l++)for(int i=1;i<=n-l+1;i++){int j = i+l-1;dp[i][j] = 0x7f7f7f7f;for(int k=s[i][j-1];k<=s[i+1][j];k++){if(dp[i][j] > dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1]){dp[i][j] = dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1];s[i][j] = k;}}}printf("%d\n",dp[1][n]);}return 0;
}