AcWing 479. 加分二叉树
原题链接
中等
作者:
回归线
,
2021-03-27 15:15:57
,
所有人可见
,
阅读 275
#include <iostream>
using namespace std;
const int N = 40;
int n;
int w[N];
int f[N][N];
int root[N][N];
void dfs(int l, int r) {
if (l > r) {
return;
}
int k = root[l][r];
cout << k << ' ';
dfs(l, k - 1);
dfs(k + 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;
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 (l == r) {
score = w[k];
}
if (f[l][r] < score) {
f[l][r] = score;
root[l][r] = k;
}
}
}
}
cout << f[1][n] << endl;
dfs(1, n);
return 0;
}