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
PROBLEM: A dynamic programming topic, for which we define DP[I][J] as the cost of the combined interval (I,J), so the state transition equation is dp[i][j]=min{dp[i][k]+dp[k+1][j]+sum[i][j]} (i <=K<=J-1), Sum[i][j] is the cost of the interval (I,J) and can be prefixed and optimized out, so the total complexity is O (n^3). The problem also requires initializing the DP array as the maximum value, and dp[i][i]=0 (1<=i<=n).
The code is as follows :
#include <cstdio> #include <cstring> #include <iostream> using namespace
Std
int a[10100],sum[10100];
int dp[101][101];
int main () {int n;
scanf ("%d", &n);
Memset (Dp,63,sizeof (DP));//Initialize for (int i=1;i<=n;i++) {scanf ("%d", &a[i]);
Sum[i]=sum[i-1]+a[i]; dp[i][i]=0;//obviously the cost of merging (I,i) is 0} for (int i=n;i>=1;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 ("%d", dp[1][n]);//The cost of the output merge interval (1,n) return 0; }