51Nod - 1021 Stone Merge (Interval DP)

【Title description】
N piles of stones are arranged in a line. Now combine the stones into a pile in an orderly manner. It is stipulated that only 2 adjacent piles of stones can be selected to merge into a new pile at a time, and the number of new piles of stones is recorded as the cost of the merger. Calculate the minimum cost of merging N piles of stones into one pile.

For example: 1 2 3 4, there are many ways to combine
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)

The total cost in parentheses shows that the first method has the lowest cost. Now, given the number of n piles of stones, calculate the minimum combined cost.
Input
Line 1: N (2 <= N <= 100)
Line 2 - N + 1: Number of N piles of stones (1 <= A i <= 10000)
 
Output
output minimum merge cost
 
Sample Input
4
1
2
3
4
Sample Output
19
【analyze】
Interval DP template questions.
Preprocess the interval sum, then enumerate the interval and breakpoint of each length, and transfer.
f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+sum[j]-sum[i-1])
 
【Code】
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn = 1000 + 100;
#define INF 0x3f3f3f3f

intmain ()
{
    int n;
    scanf("%d", &n);
    int sum[maxn];
    int f[maxn][maxn];
    memset(f, 0, sizeof(f));

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

    for ( int len ​​= 2 ; len <= n; len ++ )
    {
        for (int i = 1; i <= n; i++)
        {
            int j = i + len- 1 ;
            f[i][j] = INF;
            for (int k = i; k < j; k++)
                f[i][j] = min(f[i][j], f[i][k]+f[k+1][j] + sum[j] - sum[i-1]);
        }
    }

    printf("%d\n", f[1][n]);
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324607550&siteId=291194637