51Nod 1021 石子归并 ( 区间dp

题目描述

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)

输出

输出最小合并代价

样例

Input示例
4
1
2
3
4
Output示例
19

题意

入门题目

AC代码

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;

#define ls              st<<1
#define rs              st<<1|1
#define fst             first
#define snd             second
#define MP              make_pair
#define PB              push_back
#define LL              long long
#define PII             pair<int,int>
#define VI              vector<int>
#define CLR(a,b)        memset(a, (b), sizeof(a))
#define ALL(x)          x.begin(),x.end()
#define ber(i,s,e) for(int i=(s); i<=(e); i++)
#define rep(i,s,e) for(int i=(s); i>=(e); i--)

const int INF = 0x3f3f3f3f;
const int MAXN = 1e2+10;
const int mod = 1e9+7;
const double eps = 1e-8;

void fe() {
  #ifndef ONLINE_JUDGE
      freopen("in.txt", "r", stdin);
      freopen("out.txt","w",stdout);
  #endif
}
LL read()
{
   LL x=0,f=1;char ch=getchar();
   while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
   while (ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
   return x*f;
}
/*
区间dp 顾名思义,就是在一段区间内进行的动态规划
dp[i][j] i表示起始位置,j表示终止位置,
该定义一个数组dp[i,j]用来表示合并方法,i表示从编号为i的石头开始合并,
j表示所求区间的结尾,sum表示的是石头的数量。
*/
int dp[MAXN][MAXN], sum[MAXN][MAXN];
int arr[MAXN];
int n;

int main() {
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> arr[i];
    }
    CLR(dp,INF);
    for(int i = 1; i <= n; i++) {
        dp[i][i] = 0;
        sum[i][i] = arr[i];
    }
    // len为长度从小到大 i表示开始的位置 j表示结束的位置
    for(int len = 1; len < n; len++) {
        for(int i = 1; i<=n&&i+len<=n; i++) {
            int j = len+i;
            for(int k = i; k < j; k++) {
                sum[i][j] = sum[i][k]+sum[k+1][j];
                if(dp[i][j] > dp[i][k]+dp[k+1][j]+sum[i][j])
                    dp[i][j] = dp[i][k]+dp[k+1][j]+sum[i][j];
            }
        }
    }
    cout << dp[1][n] << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wang2332/article/details/80304455