P1040 加分二叉树 记忆化搜索
2017-09-01 20:43
387 查看
题目描述
设一个n个节点的二叉树tree的中序遍历为(1,2,3,…,n),其中数字1,2,3,…,n为节点编号。每个节点都有一个分数(均为正整数),记第i个节点的分数为di,tree及它的每个子树都有一个加分,任一棵子树subtree(也包含tree本身)的加分计算方法如下:subtree的左子树的加分× subtree的右子树的加分+subtree的根的分数。
若某个子树为空,规定其加分为1,叶子的加分就是叶节点本身的分数。不考虑它的空子树。
试求一棵符合中序遍历为(1,2,3,…,n)且加分最高的二叉树tree。要求输出;
(1)tree的最高加分
(2)tree的前序遍历
输入输出格式
输入格式:第1行:一个整数n(n<30),为节点个数。
第2行:n个用空格隔开的整数,为每个节点的分数(分数<100)。
输出格式:
第1行:一个整数,为最高加分(结果不会超过4,000,000,000)。
第2行:n个用空格隔开的整数,为该树的前序遍历。
记忆化搜索,noip2003的,第一次还T了,没救了。。。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
const int N = 35;
long long n,a
,f
[2],ans,yjq_naive;
long long dfs( int x, int l, int r ){
if( l == r ) return a[x];
long long mx1 = 0, mx2 = 0, res;
if( !f[l][x-1][0] ){
for( int i = l; i < x; i++ ){
res = dfs( i, l, x-1 );
if( res > mx1 ){
f[l][x-1][0] = i; f[l][x-1][1] = mx1 = res;
}
}
} else mx1 = f[l][x-1][1];
if( !f[x+1][r][0] ){
for( int i = x+1; i <= r; i++ ){
res = dfs( i, x+1, r );
if( res > mx2 ){
f[x+1][r][0] = i; f[x+1][r][1] = mx2 = res;
}
}
} else mx2 = f[x+1][r][1];
mx1 = mx1==0 ? 1 : mx1; mx2 = mx2==0 ? 1 : mx2;
return mx1*mx2+a[x];
}
void dfs2( int x, int l, int r ){
if( !x ) return ;
printf("%d ", x); if( l == r ) return;
dfs2( f[l][x-1][0], l, x-1 );
dfs2( f[x+1][r][0], x+1, r );
}
int main(){
scanf("%d", &n);
for( int i = 1; i <= n; i++ ) cin>>a[i];
for( int i = 1; i <= n; i++ ){
long long res = dfs( i, 1, n );
if( res > ans ){ yjq_naive = i; ans = res; }
}
cout<<ans<<endl;
dfs2( yjq_naive, 1, n );
return 0;
}
相关文章推荐
- 洛谷1040 加分二叉树
- CJOJ 1010【NOIP2003】加分二叉树 / Luogu 1040 加分二叉树(树型动态规划)
- 加分二叉树(区间动规或记忆化搜索)
- 洛谷1040加分二叉树
- P1040 加分二叉树 —— 树的遍历与区间dp引申
- 【记忆化搜索】[NOIP2003]加分二叉树 binary
- 【luogu1040】加分二叉树(dp)
- 洛谷1040 加分二叉树
- luoguP1040 区间DP(记忆化 加分二叉树
- 加分二叉树_洛谷1040_dp
- 【codevs 1090】加分二叉树(记忆化搜索)
- 洛古 1040_加分二叉树_dp
- [luoguP1040] 加分二叉树(DP)
- CJOJ 1010【NOIP2003】加分二叉树 / Luogu 1040 加分二叉树 /CodeVS 1090 加分二叉树
- 洛谷1040 加分二叉树
- luogu1040加分二叉树
- NOIP2003 洛谷1040 加分二叉树
- 【原题】【noip 2003 T2】【动态规划】加分二叉树
- 树形dp 加分二叉树 / 11.05.15
- NOIP 2003 加分二叉树