Title Description
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
Now, please help your good friend XZ design a program to get the right answer.
Enter a description
Input Description
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 description
Output Description
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.
Sample input
Sample Input
5
5 7 1) 2 10
Sample output
Sample Output
04T
3 1 2) 4 5
Data range and Tips
Data Size & Hint
N (n<=30)
Score <=100
Thinking of solving problems
A tree-shaped motion rules, because the given is the middle sequence traversal (not seen at first), so each enumeration of a node, its left is its left subtree, right is the right subtree, so you can ... Well, I really can't think of a recursive relationship, so I chose the memory search, set up two arrays, where the array f[i,j] stored the maximum value from I to J, and Root[i,j] represents the root node in I to J, with the code attached.
1 ProgramTree;2 varF,root:Array[0.. +,0.. +] ofLongint;3 I,n:longint;4 functionDFS (l,r:longint): Longint;5 varI:longint;6 begin7 iff[l,r]<>-1 Thenexit (F[l,r]);8 ifL>r Then beginf[l,r]:=1; Exit1);End;9 forI:=l toR Do//enumerate maximum and root nodesTen begin One ifF[l,r]<dfs (l,i-1) *dfs (i+1, R) +f[i,i] Then A begin -root[l,r]:=i; -F[l,r]:=dfs (l,i-1) *dfs (i+1, R) +F[i,i]; the End; - End; - exit (F[l,r]); - End; + - procedureprint (l,r:longint); + begin A ifL>r Thenexit; atWrite (Root[l,r],' ');//output pre-order traversal -Print (l,root[l,r]-1); -Print (root[l,r]+1, R); - End; - - begin in read (n); -Fillchar (F,sizeof (f), Byte (-1)); to fori:=1 toN Doread (f[i,i]); + fori:=1 toN Do - begin thef[i,i-1]:=1;//If the tree does not exist fill 1 *root[i,i]:=i;//the root of any node is its own $ End;Panax NotoginsengWriteln (DFS (1, N)); -Print1, n); the End.
Codevs 1090 plus two fork tree