The combined stone (section DP)

N with stones piled in a row, which are numbered 1,2,3, ..., N.

Each stack stones have a certain quality, can be used to describe an integer, and now you want it pile N merged into a pile of stones.

You can only merge adjacent piles, the combined price for the quality of the two piles of stones and, after merging with two piles of gravel stones adjacent to and adjacent to the new heap, merge due to the choice of a different order, the total cost of the merger is not the same.

4 for example, stones piled 1352 respectively, we can merge the first stack 2, the cost is 4 to give 452, and combined 1,2 stack, the price of 9 to give 92, and then combined to give 11, The total cost of 11 + 4 + 9 = 24;

If the second step is to merge 2,3 stack, the cost of 7, to obtain 47, combined consideration of the last 11, a total cost of 11 + 4 + 7 = 22.

The question is: to find a reasonable approach, bringing the total cost of the smallest, least-cost output.

Input Format

A first line number N represents the number of stones piled N.

The number N of the second row, each represents a mass of stones piled (no more than 1000).

Output Format

Output an integer representing the minimum cost.

data range

1N3001≤N≤300

Sample input:

4
1 3 5 2

Sample output:

22


Solution:
First, we use the f [L] [R] to create a dynamic array, which represents the set [L, R] in this interval into a pile of stones combined solution set, the minimum cost is obtained

 

 

Any such embodiment may be expressed as an independent three parts 
assume a value k between the L, R, the program can be expressed as the minimum + left + right side of both sides of the minimum combined
i.e. L --- K, K + 1- --R, S [R] -s [ l-1] of three parts

#include <bits / STDC ++ H.>
 the using  namespace STD;
 int A [ 350 ]; // beginning number of stones 
int B [ 350 ]; // prefix and 
int F [ 350 ] [ 350 ]; // dynamic programming array 
const  int INF = 1E9;
 int main () 
{ 
    int n-; 
    CIN >> n-;
     for ( int I = . 1 ; I <= n-; I ++ ) 
       CIN >> A [I];
     for ( int= I . 1 ; I <= n-; I ++) // prefix initialization 
       B [I] = B [I- . 1 ] + A [I]; 
     for ( int len = 2 ; len <= n-; len ++) // do the start 1, as if one is a set 
        for ( int L = 1 ; L + len 1 <= n-; L ++ ) 
        { 
            int R & lt = L + len 1 ; 
            F [L] [R & lt] = INF;
             for ( int K = L; K <R & lt; K ++ ) 
               F [L] [R & lt] = min (F [L] [R & lt], F [L] [K] + F [K + . 1 ] [R & lt] + B [R & lt] - B [L- . 1 ]);
            
        }
    printf("%d\n",f[1][n]);     
    return 0;
}

 

 

Guess you like

Origin www.cnblogs.com/ylrwj/p/11945073.html