http://codevs.cn/problem/1090/
题目描述 Description
设一个n个节点的二叉树tree的中序遍历为(l,2,3,…,n),其中数字1,2,3,…,n为节点编号。每个节点都有一个分数(均为正整数),记第j个节点的分数为di,tree及它的每个子树都有一个加分,任一棵子树subtree(也包含tree本身)的加分计算方法如下:
subtree的左子树的加分× subtree的右子树的加分+subtree的根的分数
若某个子树为主,规定其加分为1,叶子的加分就是叶节点本身的分数。不考虑它的空
子树。
试求一棵符合中序遍历为(1,2,3,…,n)且加分最高的二叉树tree。要求输出;
(1)tree的最高加分
(2)tree的前序遍历
现在,请你帮助你的好朋友XZ设计一个程序,求得正确的答案。
输入描述 Input Description
第1行:一个整数n(n<=30),为节点个数。
第2行:n个用空格隔开的整数,为每个节点的分数(分数<=100)
输出描述 Output Description
第1行:一个整数,为最高加分(结果不会超过4,000,000,000)。
第2行:n个用空格隔开的整数,为该树的前序遍历。
样例输入 Sample Input
5
5 7 1 2 10
样例输出 Sample Output
145
3 1 2 4 5
数据范围及提示 Data Size & Hint
n(n<=30)
分数<=100
我有话说:
这道题的思路是很清晰的枚举根节点处理左子树和右子树,最后相乘判断大小。是不错的树型DP入门。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=40;
const int INF=1044266559;
int f[maxn][maxn],tree[maxn],way[maxn][maxn];
void solve(int l,int r)
{
if(l>r)f[l][r]=1;
if(l==r){f[l][r]=tree[l];way[l][r]=l;}
if(f[l][r]!=-INF)return;
for(int i=l,t;i<=r;i++)
{
solve(l,i-1);
solve(i+1,r);
t=f[l][i-1]*f[i+1][r]+tree[i];
if(t>f[l][r])
{
f[l][r]=t;
way[l][r]=i;
}
}
}
void write(int l,int r)
{
if(l>r)return;
printf("%d ",way[l][r]);
write(l,way[l][r]-1);
write(way[l][r]+1,r);
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
scanf("%d",&tree[i]);
memset(f,-0x3f,sizeof(f));//此处注意,试输出f[1][1];
solve(1,n);
printf("%d\n",f[1][n]);
write(1,n);
return 0;
}