Plus binary tree
Title Description
A set of n nodes of the binary tree in preorder to (1,2,3, ..., n), where the number 1,2,3, ..., n is a node number. Each node has a score (both positive integers), referred to the i th fraction DI nodes, each sub-tree, and it has a plus tree, any subtree subtree (also contains tree itself) plus min is calculated as follows:
Of the left subtree of the partition subtree × subtree of the right subtree plus + fraction of root subtree.
If a sub-tree is empty, the provisions of its plus 1 divided leaves scores extra points is a leaf node itself. Irrespective of its empty tree.
Determine a preorder conform to (1,2,3, ..., n) and the highest points of the binary tree. Required output;
(1) tree of the highest points
(2) tree in preorder traversal
Input Format
Line 1: an integer n (n <30), is the number of nodes.
Line 2: n integers separated by spaces, each node as a fraction (fraction <100).
Output Format
Line 1: an integer, the highest points (Ans≤4,000,000,000).
Line 2: n integers separated by spaces, for preorder traversal of the tree.
This question is particularly feeling thinking;
First know know preorder traversal is impossible to obtain a binary tree before and after, since only then can know preorder any point when the root;
That is the most use of this particular nature, can write equation: dp [l] [r] = max {dp [l] [k-1], dp [k + 1] [r]}
dp [l] [r] denotes the R & lt preorder l (l will be less than the given topic r) to root node k, l is a left subtree root, r is the maximum right subtree root node Add points;
This time there is a doubt if l> r how to do, there is no obvious link between the l and r on behalf of this, you can return 1;
If l == r it? L This represents a leaf node, return W [l] to;
There are prior to a traversal, ideas, as long as the recording root [l] [r] can be a root;
Code:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=100010;
const int M=2000100;
const LL mod=1000007;
int n,w[100],root[100][100];
LL dp[100][100];
LL dfs1(int l,int r){
if(l>r) return 1ll;
if(dp[l][r]!=-1) return dp[l][r];
LL mmax=0;
for(int k=l;k<=r;k++){
LL sum=dfs1(l,k-1)*dfs1(k+1,r)+w[k];
if(sum>mmax){
root[l][r]=k;
mmax=sum;
}
}
return dp[l][r]=mmax;
}
void dfs2(int l,int r){
if(l>r) return;
int rt=root[l][r];
cout<<rt<<" ";
dfs2(l,rt-1);
dfs2(rt+1,r);
}
int main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>w[i];
memset(dp,-1,sizeof(dp));
for(int i=1;i<=n;i++) dp[i][i]=w[i],root[i][i]=i;
cout<<dfs1(1,n)<<endl;
dfs2(1,n);
return 0;
}