DP预处理每个区间的值,再枚举括号位置就好了
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 5005; char s[N]; int pre[N], nxt[N], n; ll dp[N][N]; void init() { pre[0] = 0; for (int i = 1; i <= n; i++) if (s[i] == '+') pre[i] = i; else pre[i] = pre[i-1]; nxt[n+1] = n+1; for (int i = n; i >= 1; i--) if (s[i] == '+') nxt[i] = i; else nxt[i] = nxt[i+1]; for (int i = 1; i <= n; i += 2) dp[i][i] = s[i]-'0'; for (int l = 3; l <= n; l += 2) { for (int i = 1; i <= n-l+1; i += 2) { int j = i+l-1; if (pre[j] < i) dp[i][j] = dp[i][j-2]*(s[j]-'0'); else dp[i][j] = dp[i][pre[j]-1] + dp[pre[j]+1][j]; } } } int main() { scanf("%s", s+1); n = strlen(s+1); init(); ll ans = dp[1][n]; for (int i = 1; i <= n; i += 2) { for (int j = i+2; j <= n; j += 2) { if (s[i-1] != '*' && s[j+1] != '*') continue; ll res = 0; if (pre[i] > 0) res += dp[1][pre[i]-1]; if (nxt[j] < n+1) res += dp[nxt[j]+1][n]; ll tmp = dp[i][j]; if (pre[i]+1 <= i-2) tmp *= dp[pre[i]+1][i-2]; if (nxt[j]-1 >= j+2) tmp *= dp[j+2][nxt[j]-1]; res += tmp; ans = max(ans, res); } } printf("%lld ", ans); }