有一个算术表达式 x1 Δ x2 Δ x3 Δ ,..., Δ xn , x1,x2,x3,...,xn 是1到 9的数字, Δ 是'+'或者'*'。
现在要求你在这个表达式中加一对括号,使得这个式子的值最大。
样例解释:3 + 5 * (7 + 8) * 4 = 303。
Input
单组测试数据。 第一给出表达式s(1 ≤ |s| ≤ 5001, |s| 是奇数),它的奇数位是1到9的数字字符,偶数位是'+'或'*'。 '*'的数目不超过15。
Output
输出最大的值。
Input示例
3+5*7+8*4
Output示例
303
枚举括号加上的位置i, j,那么括号里的值为dp[i][j],然后求出整个表达式的值更新答案
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#define maxn 5005
#define MOD 1000000007
using namespace std;
typedef long long ll;
ll d[maxn][maxn];
char str[maxn];
int main(){
// freopen("in.txt", "r", stdin);
scanf("%s", str+1);
int len = strlen(str+1);
ll k1, k2;
for(int i = 1; i <= len; i += 2){
k1 = 0, k2 = str[i] - '0';
d[i][i] = k2;
for(int j = i + 2; j <= len; j += 2){
if(str[j-1] == '+'){
k1 += k2;
k2 = str[j] - '0';
}
else{
k2 *= str[j] - '0';
}
d[i][j] = k1 + k2;
}
}
ll ans = 0;
for(int i = 1; i <= len; i += 2)
for(int j = i + 2; j <= len; j += 2){
ll p = d[i][j], v = 0;
if(i > 1){
int h;
for(h = i - 1; h >= 2; h -= 2){
if(str[h] == '*')
p *= str[h-1] - '0';
else
break;
}
if(h){
v += d[1][h-1];
}
}
if(j < len){
int h;
for(h = j + 1; h < len; h += 2){
if(str[h] == '*')
p *= str[h+1] - '0';
else
break;
}
if(h < len){
v += d[h+1][len];
}
}
p += v;
ans = max(ans, p);
}
printf("%I64d\n", ans);
return 0;
}