(区间DP)1021 石子归并

1021 石子归并

  1. 1 秒
  2.  
  3. 131,072 KB
  4.  
  5. 20 分
  6.  
  7. 3 级题

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堆石子的数量,计算最小合并代价。

 收起

输入

第1行:N(2 <= N <= 100)
第2 - N + 1:N堆石子的数量(1 <= A[i] <= 10000)

输出

输出最小合并代价

输入样例

4
1
2
3
4

输出样例

19
#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<iomanip>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=tree[rt<<1]+tree[rt<<1|1]
#define nth(k,n) nth_element(a,a+k,a+n);  // 将 第K大的放在k位
#define ko() for(int i=2;i<=n;i++) s=(s+k)%i // 约瑟夫
#define ok() v.erase(unique(v.begin(),v.end()),v.end()) // 排序,离散化
#define Catalan C(2n,n)-C(2n,n-1)  (1,2,5,14,42,132,429...) // 卡特兰数
using namespace std;

inline int read(){
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}

typedef long long ll;
const double pi = atan(1.)*4.;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
const int M=63;
const int N=1e5+5;
ll dp[105][105],sum[105];
int main(){
    int n; ll x;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%lld",&x);
        sum[i]=sum[i-1]+x;
    }
    for(int i=0;i<=n;i++){
        for(int j=0;j<=n;j++){
            if(i!=j) dp[i][j]=inf;
            else dp[i][j]=0;    
        }
    }

    //  先求 n-2 -->  n-2 的,依次累积成最小的 
    //  如果 for(int i=0;i<n-1;i++)  这么写的话,相当于 dp[0][n-1] 只求了一遍,是个固定值
    for(int i=n-2;i>=0;i--){   
        for(int j=i+1;j<n;j++){
            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("%lld\n",dp[0][n-1]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/black_horse2018/article/details/89031630