51nod 1021 Stone Merge 【Interval DP】

Base Time Limit: 1 second Space Limit: 131072 KB Score: 20Difficulty  : Level 3 Algorithm Questions
 collect
 focus on
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 each time, and the number of new piles of stones shall be 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
第1行:N(2 <= N <= 100)
2nd - N + 1: Number of N piles of stones (1 <= A[i] <= 10000)
Output
output minimum merge cost
Input example
4
1
2
3
4
Output example
19 
[Code]:
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
#include<stack>
#define maxn 105
#define maxm 50005
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;

int n;
int a[maxn];
int dp[maxn][maxn];
int sum[maxn];


intmain ()
{
    while(cin>>n)
    {
        memset(sum,0,sizeof(sum));
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++) {
            cin>>a[i];
            sum[i]=sum[i-1]+a[i];
        }
        for(int i=1;i<=n;i++)
            dp[i][i]=0;
        for(int r=2;r<=n;r++){
            for(int i=1;i<=n-r+1;i++){
                int j=i+r-1;
                dp[i][j]=INF;
                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\n",dp[1][n]);
    }
    return 0;
}

 

Guess you like

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