zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    男人只说三分话、留的七分打天下。
    sqlmap实例拿站
    sqlmap使用笔记
    rpm安装删除简介
    Zookeeper技术介绍
    linux下各文件夹的结构说明及用途介绍:
    每个系统管理员都要知道的 30 个 Linux 系统监控工具
    常用命令
    安装gitlab管理自己的代码
    速成Git
  • 原文地址:https://www.cnblogs.com/cxhscst2/p/7360362.html
Copyright © 2011-2022 走看看