Three plus points two fork tree
"Problem description"
The mid-order traversal of a two-ary tree with an n node is (l,2,3,..., N), where the number,..., n is a node number. Each node has a fraction (all positive integers), the score for the J node is di,tree and each of its subtrees has an extra point, and any subtrees tree subtree (also including the tree itself) is calculated as follows:
Subtree The xsubtree of the right subtree of the left sub-tree and the score of the root of the +subtree.
If a subtree is dominated, it is specified to be divided into 1, and the addition of leaves is the fraction of the leaf node itself. Without regard to its emptiness
Subtree
Try to find a tree of two trees that matches the middle order traversal (,..., N) and has the highest added score. Required output;
(1) Maximum bonus points for tree
(2) The tree's pre-sequence traversal
"Input Format"
Line 1th: An integer n (n<30), which is the number of nodes.
Line 2nd: n spaces separated by integers, for each node's score (fractional <100).
"Output Format"
Line 1th: An integer that is the highest plus score (the result will not exceed 4,000,000,000).
Line 2nd: N A space-separated integer, for the tree's pre-order traversal.
"Input Sample"
5
5 7 1) 2 10
"Output Example"
145
3 1 2) 4 5
Ideas
Interval DP
Set D[I][J] is the optimal construction score for the node range of IJ.
State transition equation:
D[i][j]=max (D[i][j],d[i][k-1]*d[k+1][j]+a[k])
Use memory to search for something better.
As for the output pre-order traversal, only one p[i][j] array is required, and the selections made within the IJ interval are recorded accordingly. Print traverses the output in front of the sequence.
Code
1#include <iostream>2#include <cstring>3 #definefor (A,B,C) for (int a= (b); a<= (c); a++)4 using namespacestd;5 6 Const intMAXN = -+Ten;7 intD[MAXN][MAXN],P[MAXN][MAXN];8 intA[MAXN];9 intN;Ten One intdpintSintt) { A if(D[s][t])returnD[s][t]; - - if(T<s)return 1; the if(s==t) {p[s][s]=s;returna[s];} - - For (k,s,t) { - intTMP=DP (s,k-1) *DP (k +1, T) +A[k]; + if(tmp>D[s][t]) { -d[s][t]=tmp; +p[s][t]=K; A } at } - returnD[s][t]; - } - voidPrintintSintt) { - if(!p[s][t])return ; -cout<<p[s][t]<<" "; inPrint (s,p[s][t]-1); -Print (p[s][t]+1, T); to } + intMain () { -Ios::sync_with_stdio (false); theCin>>N; *for (I,1, N) cin>>A[i]; $COUT<<DP (1, N) <<"\ n";Panax NotoginsengPrint1, n); - return 0; the}
NOIP2003 plus two forks of trees