题意:
N堆石子摆成一条线。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。
n<=100
思路:
dp[i][j]表示以i开头,长度为j的石子合并的答案
dp[i][j] = min(dp[i][k] + dp[i+k][j-k], dp[i][j] + sum(i,i+j-1));
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
#include<functional>
#include<list> #define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1
#define lowbit(x) ((x)&(-x)) using namespace std; typedef double db;
typedef long double ldb;
typedef long long ll;
typedef long long LL;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL; const db eps = 1e-;
const int mod = 1e9+;
const int maxn = 2e6+;
const int maxm = 2e6+;
const int inf = 0x3f3f3f3f;
//const db pi = acos(-1.0);
const int N = maxn; int n;
int dp[][];
int a[maxn];
int s[maxn];
int main(){
int n;
scanf("%d", &n);
mem(dp,inf);
for(int i = ; i <= n; i++){
scanf("%d", &a[i]);
dp[i][] = ;
s[i] = s[i-]+a[i];
}
for(int j = ; j <= n; j++){
for(int i = ; i+j- <= n; i++){
for(int k = ; k < j; k++){
dp[i][j] = min(dp[i][j], dp[i][k] + dp[i+k][j-k]+s[i+j-]-s[i-]);
}
//printf("%d %d %d\n",i,j,dp[i][j]);
}
}
printf("%d",dp[][n]);
return ;
} /*`
10
59 -17 5 67 87 50 -71 54 27 -10
*/