本文主要是介绍CodeForces #308 Div2 E(552E Vanya and Brackets),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
给定一个字符串 是一个只含有加法乘法的表达式 现在要在这个字符串中添加一对括号 使得表达式的答案最大
枚举添加括号的位置然后计算结果就可以了
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <string>
#include <vector>
#include <queue>
#include <stack>#define MEM(a,x) memset(a,x,sizeof a)
#define eps 1e-8
#define MOD 10009
#define MAXN 10010
#define MAXM 100010
#define INF 99999999
#define ll __int64
#define bug cout<<"here"<<endl
#define fread freopen("ceshi.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)using namespace std;int Read()
{char c = getchar();while (c < '0' || c > '9') c = getchar();int x = 0;while (c >= '0' && c <= '9') {x = x * 10 + c - '0';c = getchar();}return x;
}void Print(int a)
{if(a>9)Print(a/10);putchar(a%10+'0');
}vector<int> pos;
stack<ll> num;
stack<char> ch;ll cal(string s)
{while(!num.empty()) num.pop();while(!ch.empty()) ch.pop();for(int i=0;i<s.length();i++){char c=s[i];if(c>='0'&&c<='9')num.push(c-'0');else if(c=='('){ch.push(c);}else if(c==')'){while(ch.top()!='('){char x=ch.top(); ch.pop();ll a=num.top(); num.pop();ll b=num.top(); num.pop();if(x=='*')num.push(a*b);else num.push(a+b);}ch.pop();}else{if(c=='+'){while(!ch.empty()&&ch.top()=='*'){char x=ch.top(); ch.pop();ll a=num.top(); num.pop();ll b=num.top(); num.pop();if(x=='*')num.push(a*b);else num.push(a+b);}ch.push(c);}else ch.push(c);}}while(!ch.empty()){char x=ch.top(); ch.pop();ll a=num.top(); num.pop();ll b=num.top(); num.pop();if(x=='*')num.push(a*b);else num.push(a+b);}return num.top();
}int main()
{
// fread;string str;while(cin>>str){int n=str.size();pos.clear();pos.push_back(-1);for(int i=1;i<n;i+=2)if(str[i]=='*')pos.push_back(i);pos.push_back(n);int len=pos.size();ll ans=0;for(int i=0;i<len-1;i++){for(int j=i+1;j<len;j++){string s=str;s.insert(pos[i]+1,1,'(');s.insert(pos[j]+1,1,')');//在该位置插入一个字符ans=max(ans,cal(s));}}printf("%I64d\n",ans);}return 0;
}
这篇关于CodeForces #308 Div2 E(552E Vanya and Brackets)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!