[AcWing 479] 加分二叉树
作者:互联网
点击查看代码
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const int N = 50;
int n;
int w[N];
int f[N][N], g[N][N];
void dfs(int l, int r)
{
if (l > r)
return;
int root = g[l][r];
cout << root << ' ';
dfs(l, root - 1);
dfs(root + 1, r);
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++)
cin >> w[i];
for (int len = 1; len <= n; len ++)
for (int l = 1; l + len - 1 <= n; l ++) {
int r = l + len - 1;
if (len == 1) {
f[l][r] = w[l];
g[l][r] = l;
continue;
}
for (int k = l; k <= r; k ++) {
int left = k == l ? 1 : f[l][k - 1];
int right = k == r ? 1 : f[k + 1][r];
int score = left * right + w[k];
if (f[l][r] < score) {
f[l][r] = score;
g[l][r] = k;
}
}
}
cout << f[1][n] << endl;
dfs(1, n);
return 0;
}
- 状态表示
\(f[i][j]\) 表示将 \([l,r]\) 组成一棵树的最大分数
\(g[i][j]\) 表示 \([l,r]\) 组成树的根节点 - 状态计算
对于 \([l,r]\),枚举根节点的位置 \(k\)
① 若 \(k = l\),说明没有左子树,左子树的分数 \(left = 1\),右子树的分数 \(right = f[k + 1][r]\)
② 若 \(k = r\),说明没有右子树,右子树的分数 \(right = 1\),左子树的分数为 \(left = f[l][k - 1]\)
③ 若 $k \ \epsilon \ (l, r) $,说明有左子树和右子树,左子树的分数为 \(left = f[l][k - 1]\),右子树的分数 \(right = f[k + 1][r]\)
根节点的分数为 \(w[k]\),总的分数为 \(score = left + right + w[k]\)
当 \(score > f[l][r]\) 时,说明当前根节点的选法是更优的,更新 \(f[l][r] = score\),\(g[l][r] = k\) - 输出方案
\(dfs(1, n)\) ,每次递归处理左子树和右子树
标签:分数,左子,right,int,右子,二叉树,left,479,AcWing 来源: https://www.cnblogs.com/wKingYu/p/16456596.html