N堆石子摆成一条线。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。
例如: 1 2 3 4,有不少合并方法
1 2 3 4 => 3 3 4(3) => 6 4(9) => 10(19)
1 2 3 4 => 1 5 4(5) => 1 9(14) => 10(24)
1 2 3 4 => 1 2 7(7) => 3 7(10) => 10(20)
括号里面为总代价可以看出,第一种方法的代价最低,现在给出n堆石子的数量,计算最小合并代价。
Input
第1行:N(2 <= N <= 100) 第2 - N + 1:N堆石子的数量(1 <= A[i] <= 10000)
Output
输出最小合并代价
Input示例
4 1 2 3 4
Output示例
19
dp[i][j] : 从i到j合并的最小代价
dp[i][j] = min(dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1]) {i<=k<j}
#include <bits/stdc++.h> using namespace std; const int N = 1e3; int n, s[N], sum[N]; int dp[N][N];//从i到j合并的最小代价 int main () { scanf("%d", &n); for(int i=1;i<=n;i++) { scanf("%d",&s[i]); sum[i] = sum[i-1] + s[i]; } memset(dp,0x3f,sizeof(dp)); for(int i=1;i<=n;i++) { dp[i][i] = 0; } for(int len=2;len<=n;len++) { for(int i=1;i+len-1<=n;i++) { int j = i+len-1; 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]); } } } //cout << dp[1][2] <<endl; cout << dp[1][n] <<endl; return 0; }