石子归并 51Nod - 1021

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38177302/article/details/81367151

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

Input
第1行:N(2 <= N <= 100)
第2 - N + 1:N堆石子的数量(1 <= Aii <= 10000)

Output
输出最小合并代价

Sample Input
4
1
2
3
4

Sample Output
19

题以分析:这道题是今天写的第三道动态规划类题型了,这到题属于最优问题,最优问题一般分解为两个最优的合成一个最优的,这就和动态规划的思想一致了,有前一个状态得到下一个状态,可以想到这里,然后就应该很简单的退出来状态转移方程了吧。
dp[i][j] 的意思是i堆到j堆的最少花费的合并。
arr【i】表示前i堆的石子的总个数。
状态转移方程:dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + arr[j] - arr[i-1]);

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;

void demo(int dp[][110], int *arr, int n)
{
    for (int i = 0; i <= n; i++)
        for (int j = 0; j <= n; j++)
            dp[i][j] = (i == j)? 0 : 1e9;
    for (int i = n; i >= 1; i--)
    {
        for (int j = i+1; j <= n; j++)
        {
            for (int k = i; k <= j-1; k++)
            {
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + arr[j] - arr[i-1]);
            }
        }
    }
}

int main()
{
    int n;
    int dp[110][110];
    int arr[110];

    scanf("%d", &n);
    arr[0] = 0;
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &arr[i]);
        arr[i] += arr[i-1];
    }

    demo(dp, arr, n);
    printf("%d\n", dp[1][n]);

    return 0;
}

“`

猜你喜欢

转载自blog.csdn.net/qq_38177302/article/details/81367151