[NOIP2003 提高组] 加分二叉树 - 洛谷https://www.luogu.com.cn/problem/P1040
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <unordered_map>
#include <cmath>
#include <map>
#include <cctype>
#include <cstdlib>
#include <deque>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
int n;
ll f[105][105];
int root[105][105];
void dfs(int l, int r) {
if (l > r)
return;
printf("%d ", root[l][r]);
if (l == r)
return;
dfs(l, root[l][r] - 1);
dfs(root[l][r] + 1, r);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld", &f[i][i]);
root[i][i] = i;
f[i][i - 1] = 1;
}
for (int l = 1; l < n; l++) {
for (int i = 1; i <= n - l; i++) {
int j = i + l;
for (int k = i; k <= j; k++) {
if (k == j) {
if (f[i][j] < f[i][j - 1] + f[j][j]) {
f[i][j] = f[i][j - 1] + f[j][j];
root[i][j] = k;
}
} else if (f[i][j] < f[i][k - 1]*f[k + 1][j] + f[k][k]) {
f[i][j] = f[i][k - 1] * f[k + 1][j] + f[k][k];
root[i][j] = k;
}
}
}
}
printf("%lld\n", f[1][n]);
dfs(1, n);
return 0;
}