NYOJ737 -- Combination of stones (1)

Source: Internet
Author: User

NYOJ737 -- Combination of stones (1)
Stone Merge (a) time limit: 1000 MS | memory limit: 65535 KB difficulty: 3

There are N piles of stones in a row, and each pile of stones has a certain number. Now we want to build N piles of stones into a pile. The merge process can only pile the adjacent two piles of stones into a pile each time, the cost of each merge is the sum of the two piles of stones, after the N-1 merge into a pile. Obtain the minimum total cost.
Multiple groups of test data are input, and the input ends with the end of the file.
The first line of each group of test data has an integer n, indicating that there are n piles of stones.
The next row contains n (0 <n <200) numbers, indicating the number of these n heaps respectively. The minimum output cost is separated by spaces, which accounts for a single row of sample input.
31 2 3713 7 8 16 21 4 18
Sample output
9239
Source

Classic Problems



Interval dp, where dp [I] [j] indicates the minimum cost of merging the j heap stones from the I heap stones, then dp [I] [j] = min (dp [I] [k] + dp [k + 1] [j] + sum [I] [j])


#include   #include 
    
       #include 
     
        #include 
      
         #include 
       
          #include 
        
          #include 
         
           #include 
          
            #include 
           
             #include 
            
              #include using namespace std;const int N = 220;const int inf = 0x3f3f3f3f; int w[N];int dp[N][N];int sum[N];int main(){int n;while (~scanf("%d", &n)){sum[0] = 0;for (int i = 1; i <= n; i++){scanf("%d", &w[i]);sum[i] = sum[i - 1] + w[i];}memset (dp, 0, sizeof(dp));for (int i = n; i >= 1; i--){for (int j = i + 1; j <= n; j++){int tmp = inf;for (int k = i; k < j; k++){tmp = min(tmp, dp[i][k] + dp[k + 1][j] + sum[j] - sum[i - 1]);}dp[i][j] = tmp;}}printf("%d\n", dp[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.