Codevs 1048 Stone Merge (interval type DP)

Source: Internet
Author: User
Tags min

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; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.