Question
1100 + Binary Tree
Noip National League Promotion Group in 2003
Time Limit: 1 s space limit: 128000 kb Title Description
Description
Set the ordinal traversal of a tree with N nodes to (l, 2, 3 ,..., N), where the number is 1, 2, 3 ,..., N is the node number. Each node has a score (all positive integers). Note that the score of node J is DI, and the tree and each of its Subtrees have an extra score, the method for calculating the extra points of any subtree (also including the tree itself) is as follows:
Bonus points for the left subtree of the subtree x bonus points for the right subtree of the subtree + score for the root of the subtree
If a subtree is the primary node, it is set to 1. The leaf node scores itself. Leave it empty
Subtree.
Try to find a tree that matches the ordinal traversal (, 3 ,..., N) the tree with the highest bonus points. Output required;
(1) Top bonus points for tree
(2) tree pre-order traversal
Now, please help your good friend xz to design a program and get the correct answer.
Input description
Input description
Row 1st: an integer n (n <= 30), indicating the number of nodes.
Row 2nd: N integers separated by spaces, which are the scores of each node (score <= 100)
Output description
Output description
Row 1st: an integer that is the maximum value (the result cannot exceed 4,000,000,000 ).
Row 2nd: N integers separated by spaces, traversing the tree in the forward order.
Sample Input
Sample Input
5
5 7 1 2 10
Sample output
Sample output
145
3 1 2 4 5
Data range and prompt
Data size & hint
N (n <= 30)
Score <= 100
Question
This question is a DP, and it is better to use the memory-based search method.
Code
1/* 2 Author: wnjxyk 3 Subject: p1100 plus Binary Tree 4 */5 6 # include <cstdio> 7 # include <iostream> 8 # include <string> 9 Using namespace STD; 10 const int maxn = 30; 11 int N; 12 INT f [maxn + 10] [maxn + 10]; 13 string a [maxn + 10] [maxn + 10]; 14 int V [maxn + 10]; 15 16 inline bool ReMax (Int & A, int B) {17 if (B> A) {18 A = B; 19 Return true; 20} 21 return false; 22} 23 24 inline string I2S (int n) {25 string ans = ""; 26 while (n! = 0) {27 ans = (char) (N % 10 + '0') + ans; 28 N/= 10; 29} 30 return ans; 31} 32 33 int getans (INT left, int right) {34 if (left> right) {35 A [left] [right] = ""; 36 return 1; 37} 38 If (Left = right) {39 A [left] [right] = I2S (left); 40 return V [left]; 41} 42 if (F [left] [right]! = 0) return f [left] [right]; 43 A [left] [right] = ""; 44 for (int K = left; k <= right; k ++) {45 if (ReMax (F [left] [right], V [k] + getans (left, k-1) * getans (k + 1, right ))) A [left] [right] = I2S (k) + (A [left] [k-1]. length ()! = 0? "": "") + A [left] [k-1] + (A [k + 1] [right]. Length ()! = 0? "": "") + A [k + 1] [right]; 46} 47 return f [left] [right]; 48} 49 50 int main () {51 scanf ("% d", & N); 52 for (INT I = 1; I <= N; I ++) scanf ("% d ", & V [I]); 53 printf ("% d \ n", getans (1, N); 54 cout <A [1] [N] <Endl; 55 return 0; 56}
View code
Vijos 1100 + Binary Tree