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

题目: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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值