题目传送门
先跑dfs,枚举出所有符合题意的符号放置方式,再跑区间dp.
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int n,k,a[20],p[30]; long long ans,f[25][25]; inline int max(int s,int d) { if(s < d) return d; return s; } inline void dp() { for(int i = 1;i <= n; i++) f[i][i] = a[i]; for(int len = 1;len < n; len++) for(int i = 1,j = i + len;j <= n; i++,j++) for(int k = i;k < j; k++) if(p[k] == 1) f[i][j] = max(f[i][j],f[i][k] + f[k+1][j]); else if(p[k] == 2) f[i][j] = max(f[i][j],f[i][k] * f[k+1][j]); ans = max(ans,f[1][n]); } inline void dfs(int d,int l,int r) { if(d == n) { memset(f,0,sizeof(f)); dp(); return ; } if(l < k) { p[d] = 2; dfs(d + 1,l + 1,r); } if(r < n - k - 1) { p[d] = 1; dfs(d + 1,l,r + 1); } } int main() { scanf("%d%d",&n,&k); for(int i = 1;i <= n; i++) scanf("%d",&a[i]); dfs(1,0,0); printf("%lld",ans); return 0; }