Codeforces 552E Vanya and Brackets(枚举 + 表达式计算)
题目链接 Vanya and Brackets
题目大意是给出一个只由1-9的数、乘号和加号组成的表达式,若要在这个表达式中加上一对括号,求加上括号的表达式的最大值。
我们发现,左括号的位置肯定是最左端或者某个乘号右边,右括号的位置肯定是最右段或者某个乘号左边。
而乘号最多只有15个,那么暴力枚举就可以了。
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i(a); i <= (b); ++i)
#define dec(i, a, b) for (int i(a); i >= (b); --i)
typedef long long LL;
vector <int> pos;
LL calc(const string &str){
stack <LL> num;
stack <char> op;
for (int i = 0, slen = str.length(); i < slen; ++i) {
if (str[i] == ')'){
while (op.top() != '('){
LL tmp = num.top();
num.pop();
if (op.top() == '*') num.top() *= tmp;
else if (op.top() == '+') num.top() += tmp;
op.pop();
}
op.pop();
continue;
}
if (isdigit(str[i])) num.push(str[i] - '0');
else if (str[i] == '+' && !op.empty() && op.top() == '*'){
while (!op.empty() && op.top() == '*'){
LL tmp = num.top();
num.pop();
num.top() *= tmp;
op.pop();
}
op.push(str[i]);
}
else op.push(str[i]);
}
while(!op.empty()){
LL tmp = num.top();
num.pop();
if(op.top() == '*') num.top() *= tmp;
else if(op.top() == '+') num.top() += tmp;
op.pop();
}
return num.top();
}
int main(){
string str;
cin >> str;
pos.push_back(-1);
int slen = str.length();
for (int i = 1; i < slen; i += 2) if (str[i] == '*') pos.push_back(i);
pos.push_back(slen);
slen = pos.size();
LL ret = INT_MIN;
rep(i, 0, slen - 2)
rep(j, i + 1, slen - 1){
string s = str;
s.insert(pos[i] + 1, 1, '(');
s.insert(pos[j] + 1, 1, ')');
ret = max(ret, calc(s));
}
cout << ret << endl;
return 0;
}

浙公网安备 33010602011771号