P1040 加分二叉树【dp+深搜】

这是一道关于二叉树构造的问题,目标是构建一个中序遍历为1到n的二叉树,使得其加分最高。加分计算方式是左子树加分乘以右子树加分加上根节点的分数,空子树加分视为1。输入包括节点数量n和每个节点的分数,输出是最高加分和前序遍历序列。给定的输入样例展示了如何解决这个问题并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
设一个nn个节点的二叉树tree的中序遍历为(1,2,3,…,n1,2,3,…,n),其中数字1,2,3,…,n1,2,3,…,n为节点编号。每个节点都有一个分数(均为正整数),记第ii个节点的分数为di,treedi,tree及它的每个子树都有一个加分,任一棵子树subtreesubtree(也包含treetree本身)的加分计算方法如下:

subtreesubtree的左子树的加分× subtreesubtree的右子树的加分+subtreesubtree的根的分数。

若某个子树为空,规定其加分为11,叶子的加分就是叶节点本身的分数。不考虑它的空子树。

试求一棵符合中序遍历为(1,2,3,…,n1,2,3,…,n)且加分最高的二叉树treetree。要求输出;

(1)treetree的最高加分

(2)treetree的前序遍历

输入格式
第11行:11个整数n(n<30)n(n<30),为节点个数。

第22行:nn个用空格隔开的整数,为每个节点的分数(分数 <100<100)。

输出格式
第11行:11个整数,为最高加分(Ans \le 4,000,000,000≤4,000,000,000)。

第22行:nn个用空格隔开的整数,为该树的前序遍历。

输入输出样例
输入 #1 复制
5
5 7 1 2 10
输出 #1 复制
145
3 1 2 4 5

代码:

//#pragma GCC optimize(3,"Ofast","inline")
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue<int,vector<int> ,greater<int> >q;
const int maxn = (int)1e5 + 5;
const ll mod = 1e9+7;
int score[35];
int dp[35][35];
void print(int l,int r) {
    if(l==r) {
        printf("%d ",l);
        return ;
    }
    if(l>r) return ;
    for(int i=l;i<=r;i++) {
        if(dp[l][r]==dp[l][i-1]*dp[i+1][r]+score[i]) {
            printf("%d ",i);
            print(l,i-1);
            print(i+1,r);
            return ;
        }
    }
}
int main() 
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    #endif
    //ios::sync_with_stdio(0),cin.tie(0);
    int n;
    scanf("%d",&n);
    rep(i,0,n+1) {
        rep(j,0,n+1) {
            dp[i][j]=1;
        }
    }
    rep(i,1,n) {
        scanf("%d",&score[i]);
        dp[i][i]=score[i];
    }
    score[0]=score[n+1]=1;
    for(int i=n;i>=1;i--) {
        for(int j=i;j<=n;j++) {
            for(int k=i;k<=j;k++) {
                if(dp[i][k-1]==1&&dp[k+1][j]==1) dp[i][j]=max(dp[i][j],score[k]);
                else dp[i][j]=max(dp[i][j],dp[i][k-1]*dp[k+1][j]+score[k]);
            }
        }
    }
    printf("%d\n",dp[1][n]);
    print(1,n);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值