添加链接描述
区间dp
#include<bits/stdc++.h>
#define ll long long
#define x first
#define y second
#define ios ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
using namespace std;
const int M=35,INF=0x3f;
int a[M],dp[M][M],g[M][M];
void dfs(int l,int r)
{
int k=g[l][r];
if(l==r)
cout<<l<<" ";
if(!k)
return ;
cout<<k<<" ";
dfs(l,k-1);
dfs(k+1,r);
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
dp[i][i]=a[i];
}
for(int len=2;len<=n;len++)
{
for(int l=1;l+len-1<=n;l++)
{
int r=l+len-1;
if(dp[l][r]<dp[l+1][r]+a[l])
{
dp[l][r]=dp[l+1][r]+a[l];
g[l][r]=l;
}
for(int k=l+1;k<r;k++)
if(dp[l][r]<dp[l][k-1]*dp[k+1][r]+a[k])
{
dp[l][r]=dp[l][k-1]*dp[k+1][r]+a[k];
g[l][r]=k;
}
if(dp[l][r]<dp[l][r-1]+a[r])
{
dp[l][r]=dp[l][r-1]+a[r];
g[l][r]=r;
}
}
}
cout<<dp[1][n]<<endl;
dfs(1,n);
return 0;
}