P1040 加分二叉树 记忆化搜索

来源:互联网 发布:斗地主辅助软件 编辑:程序博客网 时间:2024/05/29 07:10

题目描述

设一个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[N],f[N][N][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;}


原创粉丝点击