479. 加分二叉树
作者:
qbz666
,
2021-11-09 10:21:16
,
所有人可见
,
阅读 231
#include <bits/stdc++.h>
using namespace std;
const int N = 50;
pair<int, int>PII;
unsigned f[N][N];
int root[N][N];
int n;
int w[N];
void dfs(int l, int r)
{
if (l > r)return;
cout << root[l][r] << ' ';
dfs(l, root[l][r] - 1);
dfs(root[l][r] + 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);
}