7
1+2*3/4
2
#pragma GCC optimize(2) #include<bits/stdc++.h> using namespace std; //c(n,k)*c(m,k)*k! inline int read() { int x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f; } const int maxn=1e5+10; const int mod=1e9+7; stack<char>c; stack<int>v; int n; char a[1000]; char s[1001]; int cnt,val[1001]; int check(char a,char b){ if(a==‘(‘||b==‘(‘){ return 0; } if(a==‘+‘||a==‘-‘){ return 1; } if(a==‘*‘&&(b==‘*‘||b==‘/‘)){ return 1; } if(a==‘/‘&&(b==‘*‘||b==‘/‘)){ return 1; } return 0; } int dd(int x,char p,int y){ if(p==‘+‘){ return x+y; } else if(p==‘-‘){ return x-y; } else if(p==‘*‘){ return x*y; } else{ return x/y; } } int main(){ memset(s,0,sizeof(s)); cin>>n; scanf("%s",a); a[n]=‘)‘; c.push(‘(‘); cnt=0; int i=0; while(i<=n){ if(a[i]>=‘0‘&&a[i]<=‘9‘){ int x=0; while(a[i]>=‘0‘&&a[i]<=‘9‘){ x=x*10+(a[i]-‘0‘); i++; } val[cnt++]=x; } else{ if(a[i]==‘)‘){ while(!c.empty()&&c.top()!=‘(‘){ s[cnt++]=c.top(); c.pop(); } c.pop(); } else{ while(!c.empty()&&check(a[i],c.top())){ s[cnt++]=c.top(); c.pop(); } c.push(a[i]); } i++; } } for(i=0;i<cnt;i++){ if(!s[i]){ v.push(val[i]); } else{ int y=v.top(); v.pop(); int x=v.top(); v.pop(); v.push(dd(x,s[i],y)); } } printf("%d",v.top()); }
原文:https://www.cnblogs.com/lipu123/p/12895739.html