板子题
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 <= Ai <= 10000)
Output
输出最小合并代价
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define ll long long
#define MT(a,b) memset(a,b,sizeof(a))
const int maxn=1E5+5;
const int ONF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
int stone[105];
int sum[105];
int dp[105][105];
int main (){
int n;
MT(dp,INF);
MT(sum,0);
scanf ("%d",&n);
for (int i=1;i<=n;i++){
dp[i][i]=0;
scanf("%d",&stone[i]);
sum[i]=sum[i-1]+stone[i];
}
for (int len=1;len<=n;len++){
for (int start=1;start+len<=n+1;start++){
int finish=start+len-1;
for (int tmp=start;tmp<finish;tmp++){
dp[start][finish]=min(dp[start][finish],dp[start][tmp]+dp[tmp+1][finish]+sum[tmp]-sum[start-1]+sum[finish]-sum[tmp]);
//这里可以优化成sum[finish]-sum[start-1]
}
}
}
printf("%d\n",dp[1][n]);
return 0;
}rintf("%d\n",dp[1][n]);
return 0;
}
状态转移方程:
dp[start][finish]=min(dp[start][finish],dp[start][tmp]+dp[tmp+1][finish]+weight;
其中start是区间起点,tmp是分割点,finish是区间终点