Merge nyoj 737 stones (1)

Source: Internet
Author: User

Analysis:

This topic is range-based Dynamic Planning. DP [I] [J] indicates the minimum cost of merging the I-th heap into the J-th heap,

Sum [I] [I] indicates the sum of the stones from the I heap to the J heap, then the dynamic transfer equation is as follows:

DP [I] [J] = min (DP [I] [J], DP [I] [k] + dp [k + 1] [J] + sum [I] [J]) (I <= k <= J-1 ).

The Code is as follows:

1 # include <cstdio> 2 # include <iostream> 3 # include <algorithm> 4 using namespace STD; 5 const int maxn = 200 + 5; 6 const int INF = 1000000000; 7 int DP [maxn] [maxn], sum [maxn] [maxn], stone [maxn]; 8 int main () 9 {10 int N; 11 int I, j, k; 12 while (~ Scanf ("% d", & N) 13 {14 for (I = 1; I <= N; I ++) 15 scanf ("% d ", & stone [I]); 16 for (I = 1; I <= N; I ++) 17 {18 DP [I] [I] = 0; // not merged, cost: 019 sum [I] [I] = stone [I]; 20 for (j = I + 1; j <= N; j ++) 21 Sum [I] [J] = sum [I] [J-1] + stone [J]; 22} 23 for (INT DUI = 2; DUI <= N; DUI ++) // The number of heap stones merged 24 {25 for (I = 1; I <= N-DUI + 1; I ++) // from heap I to heap J 26 {27 J = DUI + I-1; 28 DP [I] [J] = inf; 29 for (k = I; k <= J-1; k ++) 30 DP [I] [J] = min (DP [I] [J], DP [I] [k] + dp [k + 1] [J] + sum [I] [J]); 31} 32} 33 printf ("% d \ n", DP [1] [N]); 34} 35 return 0; 36}
View code

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.