[Swustoj 404] minimum cost tree

Source: Internet
Author: User

Minimum cost tree (0404)

Problem description

The following method is called the minimum cost of the letter tree: Given a sequence of positive integers, for example: 4,1,2,3, adding them without changing the position of the number, and using parentheses to mark the sum of each addition.
For example: ((4+1) + (2+3)) = ((5) + (5)) = 10. Except the original number is not 4,1,2,3, the rest are intermediate results, such as 5,5,10, add the intermediate results, get: 5+5+10= 20, then the number 20 is called the price of this sequence, if you get another algorithm: (4+ ((1+2) +3) = (4+ ((3) +3)) = (The 4+ (6)) = 10, the other cost of the sequence is: 3+6+10=19. If the number of n is given, the minimum cost of this sequence can be calculated by adding N-1 to the parentheses.
Note: The result range does not exceed longint.

Input

The first behavior is n (1≤n≤200), the second behaves n positive integers, and the integers are separated by a space.

Output

The output is only one row, which is the minimum generation value.

Sample input

4
4 1 2 3

Sample output

19

Simple Interval DP,

#include <iostream>#include<cstring>#include<algorithm>#include<cstdio>#include<cmath>using namespacestd;#definell Long Long#defineMOD 1000000007#defineINF 0x3f3f3f3f#defineN 310intA[n];intSum[n];intDp[n][n];//Dp[i][j] Indicates the minimum cost of interval i,jintMain () {intN; intI,j,k,len;  while(SCANF ("%d", &n)! =EOF) {memset (Dp,inf,sizeof(DP));  for(i=1; i<=n;i++) {scanf ("%d",&A[i]); Sum[i]=sum[i-1]+A[i]; Dp[i][i]=0; }         for(len=1; len<=n;len++){             for(i=1; i<=n-len+1; i++) {J=i+len-1;  for(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;}

[Swustoj 404] minimum cost tree

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.