cf #308 E. Vanya and Brackets (暴力枚举)

来源:互联网 发布:嵌入式编程入门 编辑:程序博客网 时间:2024/05/18 18:14

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

题意:给你一个只有+和*的表达式,让你添加一对括号使得表达式的值最大。其中*号最多15个。

分析:明显先+后*算出的结果更大,所以,用*把表达式分开,然后枚举相连的情况就好了。

ps:回顾了一下stringstream的用法。

代码:

#include <bits/stdc++.h>using namespace std;typedef long long LL;typedef unsigned long long ULL;const LL INF = 1E9+9;LL process(string &str,int x,int y){if(x>y)return 0;stringstream ss;ss<<str;LL ret=0;stack <LL > st;char ch;while(ss>>ch){if(ch=='+'){LL d;ss>>d;st.push(d);}else if(ch=='*'){LL d;ss>>d;   d=d*st.top();st.pop();st.push(d); }else{ss.unget();LL d;ss>>d;st.push(d);}}ret=st.top();st.pop();while(!st.empty()){ret=ret+st.top();st.pop();}//cout<<str<<"  :"<<ret<<endl;//system("pause");return ret;}string pro(LL x){string ret;while(x){ret.push_back(x%10+'0');x/=10;}int len=ret.size();for(int i=0,j=len-1;i<len/2;i++,j--)swap(ret[i],ret[j]);return ret;}typedef pair <int,int> pii;pii interval[20]; int main(){string str;cin>>str;str.push_back('*');int p=-1,cnt=0;for(int i=0;i<str.size();i++){if(str[i]=='*'){interval[cnt++]=make_pair(p+1,i-1);p=i;}}str.erase(--str.end());//for(int i=0;i<cnt;i++)//printf("%d %d\n",interval[i].first,interval[i].second);LL Max=process(str,0,str.size()-1);for(int i=0;i<cnt;i++){for(int j=i;j<cnt;j++){int x=interval[i].first;int y=interval[j].second;string cal=str.substr(x,y-x+1);LL temp=process(cal,0,cal.size()-1);static string s;s.clear();//printf("[ %d %d ] ",x,y);//cout<<cal<<endl;cal.clear();if(x==0){if(y==str.size()-1){}else{s=pro(temp)+str.substr(y+1);temp=process(s,0,s.size()-1);}}else{if(y==str.size()-1){s=str.substr(0,x)+pro(temp);temp=process(s,0,s.size()-1);}else{s=str.substr(0,x)+pro(temp)+str.substr(y+1);temp=process(s,0,s.size()-1);}}Max=max(Max,temp);//cout<<s<<"      <-s\n"; }}cout<<Max;return 0;}


0 0
原创粉丝点击