Merge stones (interval dp)

Description] [Title
in a row to a playground N placed stones piled. Stone is to have the order to merge into a pile. Provisions can only choose two adjacent pile into a new pile of stones, a pile of stones and a few new record for the combined score.

The calculated N merge into a pile of stones piled minimum score.

[Input]
The first line a positive integer N (2≤N≤100);

The following N lines, each a positive integer less than 10,000, respectively, represents the number of (1≤i≤N) the i-th stack stones.

[Output]
a positive integer, i.e., the minimum score.

[] Input sample
. 7
13 is
. 7
. 8
16
21 is
. 4
18 is
[] Sample Output
239

Topic analysis:

This is a range dp template title, have good learning value for beginners like me.
According to the characteristics of dynamic programming, the nature of our problems from the point of view, no matter how large the number of stones heap, will eventually be converted into two piles of stones merge, so we can put all the stones beginning divided into two parts, divided discontinuities is uncertain, we can enumerate all cases. Provided dp [i] [j] represents the minimum cost from i to merge stones j. We need to get the final answer is dp [1] [n], so we can get the answer by recursive, where 1 is the starting point of the interval, and n is the end, then we enumerate all the starting point and end all.
To obtain a state transition equation: DP [I] [J] = min (DP [I] [J], DP [I] [K] + DP [K +. 1] [J] + SUM (I, J)).
wherein the sum (i, j) for all i from stones takes combined to j, and can be used to get the prefix.

#include<iostream>
#include<cstring>
using namespace std;
int s[101];
int dp[101][101];
int main()
{
    int n,fen;
    memset(dp,127,sizeof(dp));
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>fen;
        s[i]=s[i-1]+fen;
        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]+s[j]-s[i-1]);
    }
    cout<<dp[1][n];
    return 0;
}
发布了42 篇原创文章 · 获赞 42 · 访问量 9318

Guess you like

Origin blog.csdn.net/amazingee/article/details/104378536