Luo Gu -1040 plus binary tree

Description Title
provided a binary tree of n nodes in preorder as (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:
plus right subtree of the left subtree subtree plus × subtree of the root of the subtree + fraction.
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 highest points
(2) of the preamble tree traversal
input and output format
input format:
Line 1: an integer n (n <30), is the number of nodes.
Line 2: nnn 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.

Sample Input Output
Input Sample # 1:
. 5
. 5. 7 1 2 10

Output Sample # 1:
145
. 3 1 2. 4. 5

Explanation: We can enumerate each child root node, then violence calculate the optimal solution can be found in the enumeration memory of it, so we define dp [l] [j] is the largest constructor from l to r tree value, calculated during the recording process on the OK

#include<iostream>
#define N 35
using namespace std;
long long dp[N][N]={0};
int pre[N][N]={0};
long long a[N]={0};
int n=0;
long long dfs(int l,int r,int fal,int far){
    if(r<l){
        if(fal==far) return 0;
        else return 1;
    }
    if(dp[l][r]) return dp[l][r];
    for(int mid=l;mid<=r;mid++){
        long long A=dfs(l,mid-1,l,r),B=dfs(mid+1,r,l,r);
        if(a[mid]+A*B>dp[l][r]){
            dp[l][r]=a[mid]+A*B;
            pre[l][r]=mid;
        }
    }
    return dp[l][r];
}
void print(int l,int r){
    int mid=pre[l][r];
    if(r<l) return;
    cout<<mid<<" ";
    print(l,mid-1);
    print(mid+1,r);
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    dfs(1,n,1,n);
    cout<<dp[1][n]<<endl;
    print(1,n);
    return 0;
}


Guess you like

Origin blog.csdn.net/mkopvec/article/details/91994670