1048 Stone Merge
Time limit: 1 s
Space limit: 128000 KB
Title Level: Golden Gold
Exercises
View Run Results
Title Description Description
There are n heap of stones in a row, each pile of stones have a weight of w[i], each merge can merge adjacent two piles of stones, the cost of a merger is the weight of two piles of stone and w[i]+w[i+1]. Ask what sort of merger sequence it takes to minimize the total merger cost.
Enter a description input Description
First line an integer n (n<=100)
Second row n integers w1,w2...wn (wi <= 100)
Outputs description Output Description
An integer representing the minimum consolidation cost
Sample input to sample
4
4 1 1 4
Sample output Sample Outputs
18
Standard interval DP
Sum[i] Record stone quality prefixes and
DP[I][J] Minimum cost from the start of heap I to the J heap, closed intervals (including i,j)
First, the interval right endpoint is 2, then the 3,4,5......N is obtained.
Enumerate from right to left
Code See below
#include <iostream> #include <cstdio> #include <cmath> #include <
Cstring> #include <algorithm> using namespace std;
const int MAXN = 202;
int N,X,SUM[MAXN],DP[MAXN][MAXN];
int main () {memset (dp,0x3f,sizeof (DP));
scanf ("%d", &n);
for (int i = 1; I <= n; i + +) {scanf ("%d", &x);
Sum[i] = sum[i-1] + x;
Dp[i][i] = 0; } for (int i = n-1; 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] + sum[j]-sum[i-1]);
printf ("%d\n", Dp[1][n]);
return 0; }