51nod-1452 加括号

原题链接

题目来源:  CodeForces
基准时间限制:1 秒 空间限制:524288 KB 分值: 80  难度:5级算法题
 收藏
 关注

有一个算术表达式  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
d[i][j]表示str[i]到str[j]这个表达式的值

枚举括号加上的位置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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值