noip2011普及组第四题

要用栈写比较方便,速度也还挺快O(n),主要是每遇到一个非括号符号就插两个数进数字栈里,遇到符号就从优先级入手,比如匹配到加号然后栈里面有乘号就要先解决栈里面的乘号,直到遇到‘(’符号为止。

有一个小技巧就是开头先再字符串后面加一个‘)’,再把左括号加入栈内。等下就不用去清栈,可以保证运行完后栈必空。

#include<cstdio>
#include<stack>
#include<cstring>
#define mod 10007
#include<algorithm>
using namespace std;
int l;
char s[100011];
stack<int>v0,v1;
stack<char> t;
void add()
{
	int ans0, ans1;
	int r0=v0.top();v0.pop();
	int p0=v0.top();v0.pop();
	int r1=v1.top();v1.pop();
	int p1=v1.top();v1.pop();
	ans0=(p0*r0)%mod;
	ans1=((p0*r1)%mod+(p1*(r0+r1))%mod)%mod;
	v0.push(ans0);
	v1.push(ans1);
}
void mul()
{
	int ans0, ans1;
	int r0=v0.top();v0.pop();
	int p0=v0.top();v0.pop();
	int r1=v1.top();v1.pop();
	int p1=v1.top();v1.pop();
	ans0=((p1*r0)%mod+(p0*(r0+r1))%mod)%mod;
	ans1=(p1*r1)%mod;
	v0.push(ans0);
	v1.push(ans1);
}
int main()
{
	scanf("%d", &l);
	scanf("%s", s);
	s[l++]=')';s[l]='\0';
	t.push('(');v0.push(1);v1.push(1);
	for(int i=0;i<l;i++){
		if(s[i]=='('){ t.push(s[i]); continue;}
		if(s[i]=='*'){
			while(t.top()=='*'){mul(); t.pop();}
			t.push('*');
		}if(s[i]=='+'||s[i]==')'){
			while(!t.empty()&&t.top()!='('){
				if(t.top()=='+') add();
				else mul();
				t.pop();
			}
			if(s[i]=='+') t.push('+');
			else t.pop();
		} if(s[i]!=')') { v0.push(1);v1.push(1);};
	}
	printf("%d\n", v0.top());
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值