P1040 + Binary Tree, p1040 + Binary Tree
Description
Set the central traversal of a tree with n nodes to (1, 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 I is di. The tree and each of its Subtrees have a plus score, the method for calculating the extra points of any subtree (also including the tree itself) is as follows:
Plus points for the left subtree of the subtree × plus points for the right subtree of the subtree + scores for the root of the subtree.
If a subtree is empty, set it to 1. The leaf score is the score of the leaf node. Ignore its 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
Input/Output Format
Input Format:
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 Format:
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.
Input and Output sample
Input example #1:
55 7 1 2 10
Output sample #1:
1453 1 2 4 5
Interval DP.
Recurrence won't write, and then write memory will search...
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 using namespace std; 6 const int MAXN=51; 7 int n,zx[MAXN]; 8 int dp[MAXN][MAXN]; 9 int root[MAXN][MAXN];10 void read(int & n)11 {12 char c='+';int x=0;bool flag=0;13 while(c<'0'||c>'9')14 {c=getchar();if(c=='-')flag=1;}15 while(c>='0'&&c<='9')16 {x=x*10+(c-48);c=getchar();}17 flag==1?n=-x:n=x;18 }19 int M_s(int l,int r)20 {21 dp[l][r]=1;22 if(l==r)23 {24 dp[l][r]=zx[l];25 root[l][r]=l;26 return zx[l];27 }28 else for(int k=l;k<=r;k++)29 {30 int lson=1,rson=1;31 if(dp[l][k-1])32 lson=dp[l][k-1];33 else if(l<=k-1)34 lson=M_s(l,k-1);35 if(dp[k+1][r])36 rson=dp[k+1][r];37 else if(r>k)38 rson=M_s(k+1,r);39 if(lson*rson+zx[k]>dp[l][r])40 {41 dp[l][r]=lson*rson+zx[k];42 root[l][r]=k;43 }44 }45 return dp[l][r];46 }47 void xianxu(int l,int r)48 {49 if(root[l][r])50 {51 printf("%d ",root[l][r]);52 xianxu(l,root[l][r]-1);53 xianxu(root[l][r]+1,r);54 }55 }56 int main()57 {58 read(n);59 for(int i=1;i<=n;i++)60 read(zx[i]);61 int out=M_s(1,n);62 printf("%d\n",out);63 xianxu(1,n);64 return 0;65 }