加分二叉树
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的前序遍历
Input
输入有多组数据,对于每一组数据:
第1行:一个整数n(n<30),为节点个数。
第2行:n个用空格隔开的整数,为每个节点的分数(分数<100)。
Output
对于每组数据:
第1行:一个整数,为最高加分(结果不会超过4,000,000,000)。
第2行:n个用空格隔开的整数,为该树的前序遍历。
Sample Input
5
5 7 1 2 10
5
5 7 1 2 10
Sample Output
145
3 1 2 4 5
145
3 1 2 4 5
Hint
输出第二行的数用:printf("%3d",xxx);
Source N0IP2003提高组
分析:这题只要先区间动态规划,+树的遍历即可
代码:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cmath>
#include<memory>
#include<algorithm>
#include<string>
#include<climits>
#include<queue>
#include<vector>
#include<cstdlib>
#include<map>
using namespace std;
const int ee = 50, e= -999999999;
int n;
long long a[ee]={0}, f[ee][ee],root[ee][ee]={0};
//f[i][j]为中序遍历的最大加分
void front(int x,int y)
{
if(root[x][y]!=0)
printf("%3d",root[x][y]);
if(root[x][root[x][y]-1]!=0) front(x,root[x][y]-1);
if(root[ root[x][y]+1 ][y]!=0) front(root[x][y]+1,y);
}
int main()
{
while(cin >> n)
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<=n;j++)
f[i][j]=1;
}
for(int i=1;i<=n;i++)
{
cin>>a[i];
f[i][i]=a[i];
root[i][i]=i;
}
for(int len =1;len<=n;len++)
{
for(int i=1;i<=n;i++)
{
int j=i+len;
if(j<=n)
{
long long temp=e;
for(int k=i;k<=j;k++)
{
if(temp<(f[i][k-1]*f[k+1][j]+a[k]))
{
temp=f[i][k-1]*f[k+1][j]+a[k];
root[i][j]=k;//标记根
}
}
f[i][j]=temp;
}
}
}
cout<< f[1][n] <<endl;
front(1,n);//输出前序遍历
cout<<endl;
}
return 0;
}