看完之后感觉和之前做的题目有点像区间dp的问题,枚举长度和根节点,左儿子乘右儿子加上根节点就可以了。但不知道怎么来表示这个二叉树和如何保留前序排列这里就去看了看别人的思路,结果连答案都没整明白,没办法就拿纸和笔按照那个别人写的画了一遍,然后就问题解决。用二维数组可以表示这个的二叉树因为空的节点可以用一来表示。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#define ll long long
#define fre(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout);
using namespace std;
const int MAX=2147483647;
const int N=1e2+10;
ll n,a[N],f[N][N],root[N][N];
void p(ll l,ll r)
{
if(root[l][r]) cout<<root[l][r]<<" ";
if(root[l][root[l][r]-1]) print(l,root[l][r]-1);
if(root[root[l][r]+1][r]) print(root[l][r]+1,r);
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>f[i][i];
f[i][i-1]=1;
root[i][i]=i;
}
for(int len=1;len<n;len++)
{
for(int i=1;i+len<=n;i++)
{
int j=i+len;
for(int k=i;k<=j;k++)
{
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;
}
}
}
}
cout << f[1][n] << endl;
p(1, n);
}