CF552E 字串 表示式求值

life4711發表於2015-06-27

http://codeforces.com/contest/552/problem/E

E. Vanya and Brackets
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign  represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.

Input

The first line contains expression s (1 ≤ |s| ≤ 5001|s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * .

The number of signs  *  doesn't exceed 15.

Output

In the first line print the maximum possible value of an expression.

Sample test(s)
input
3+5*7+8*4
output
303
input
2+3*5
output
25
input
3*4*5
output
60
Note

Note to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.

Note to the second sample test. (2 + 3) * 5 = 25.

Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).

/**
CF552E 字串 表示式求值
題目大意:給定一個字串只是做1~9之間的加法和乘法,現在在表示式中加上一對括號,問如何加才能使表示式的值最大
解題思路:左括號必須在一個*的後面,右括號必須在一個*的前面,如果不是這樣一定不是最優。有了這個結論,分成三部分算一下就可以了
*/
#include <string.h>
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
typedef long long LL;
char s[5005];
int n,a[105];
LL get(int l,int r)
{
    LL ans=0,tmp=1;
    for(int i=l;i<=r;i++)
    {
        if(isdigit(s[i]))
        {
            tmp*=s[i]-'0';
        }
        if(s[i]=='+')
        {
            ans+=tmp;
            tmp=1;
        }
    }
    ans+=tmp;
    tmp=1;
    LL sum=0;
    for(int i=0;i<n;i++)
    {
        if(i==l)
        {
            tmp*=ans;
            i=r;
        }
        else
        {
            if(isdigit(s[i]))
            {
                tmp*=s[i]-'0';
            }
            if(s[i]=='+')
            {
                sum+=tmp;
                tmp=1;
            }
        }
    }
    sum+=tmp,tmp=1;
   // printf(">>>%d %d %d %d\n",l,r,ans,sum);
    return sum;
}
int main()
{
    scanf("%s",s);
    n=strlen(s);
    int k=0;
    a[k++]=0;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='*')
        {
            a[k++]=i-1;
            a[k++]=i+1;
        }
    }
    if(a[k-1]!=n-1)
        a[k++]=n-1;
    LL maxx=0;
    for(int i=0;i<k;i++)
    {
        for(int j=i;j<k;j++)
        {
            LL t=get(a[i],a[j]);
            maxx=max(maxx,t);
        }
    }
    printf("%lld\n",maxx);
    return 0;
}


相關文章