noip2011普及组第四题

来源:互联网 发布:linux下安装lamp 编辑:程序博客网 时间:2024/06/06 01:37

要用栈写比较方便,速度也还挺快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
原创粉丝点击