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