nyoj 1272 表达式求值
2017-04-17 08:55
351 查看
表达式求值
表达式求值基础:表达式求值基础题
ps:对Smax预处理一下,转换成普通的表达式就行了
代码:
#include<stdio.h> #include<math.h> #include<string.h> #include<stack> #include<algorithm> using namespace std; #define max(a,b) (a>b?a:b) stack<char>s1,s2; stack<int>s3; char str[1010],ch[1010]; int len; void pretreatment(int n)//预处理 { len=0; for(int i=0; i<n; ++i) { if(str[i]=='S') { i+=5; ch[len++]='('; while(str[i]!=',') 4000 ch[len++]=str[i++]; ch[len++]=')'; ch[len++]='S'; ch[len++]='('; i++; while(str[i]!=')') ch[len++]=str[i++]; ch[len++]=')'; } else ch[len++]=str[i]; } ch[len]='\0'; } int priority(char c)//优先级比较 { if(c=='(') return 5; if(c=='S') return 4; if(c=='*') return 3; if(c=='+') return 2; if(c==')') return 1; } int Scal(int a,int b,char op)//进行运算 { if(op=='+') return a+b; if(op=='*') return a*b; if(op=='S') { int x=0,y=0; while(a) { x+=a%10; a/=10; } while(b) { y+=b%10; b/=10; } return max(x,y); } } void Transform()//转化为后缀表达式 { for(int i=0; i<len; ++i) { if(ch[i]>='0'&&ch[i]<='9') { if(i+1<len&&(ch[i+1]<'0'||ch[i+1]>'9')||i==len-1) { s2.push(ch[i]); s2.push('#'); } else s2.push(ch[i]); } else { if(s1.empty()||ch[i]=='('||priority(ch[i])>priority(s1.top())) s1.push(ch[i]); else if(ch[i]==')') { while(s1.top()!='(') { s2.push(s1.top()); s1.pop(); } s1.pop(); } else { while(!s1.empty()&&priority(ch[i])<=priority(s1.top())&&s1.top()!='(') { s2.push(s1.top()); s1.pop(); } s1.push(ch[i]); } } } int k=0; while(!s2.empty()) { s1.push(s2.top()); s2.pop(); } while(!s1.empty()) { ch[k++]=s1.top(); s1.pop(); } ch[k]='\0'; } int Cal(int n) { int x,y; for(int i=0; i<n; ++i) { if(ch[i]=='#') continue; else if(ch[i]=='+'||ch[i]=='*'||ch[i]=='S') { x=s3.top(); s3.pop(); y=s3.top(); s3.pop(); x=Scal(y,x,ch[i]); s3.push(x); } else { int result=0; while(ch[i]>='0'&&ch[i]<='9') { result=result*10+ch[i]-'0'; i++; } s3.push(result); } } return s3.top(); } int main() { int t; scanf("%d",&t); while(t--) { scanf("%s",str); pretreatment(strlen(str)); Transform(); printf("%d\n",Cal(strlen(ch))); } return 0; }
相关文章推荐
- nyoj 1272 表达式求值
- nyoj1272 zzulioj1923表达式求值(河南省acm第九届省赛)
- nyoj 1272 表达式求值
- NYOJ1272 表达式求值(后缀求值,特殊处理)(河南省第九届ACM省赛)
- nyoj 1272 表达式求值
- 2016 河南省第九届ACM程序设计大赛 nyoj 1272 表达式求值
- nyoj 1272 表达式求值
- NYOJ 1272 表达式求值 (字符串处理)
- nyoj1272表达式求值(递归法)
- nyoj 1272 表达式求值
- nyoj 1272 表达式求值
- 【表达式求值】中缀表达式变后缀+后缀表达式的求法 (NYOJ 35+NYOJ 1272表达式求值)
- nyoj 1272 表达式求值(中缀式转后缀式)
- NYOJ_1272_表达式求值
- nyoj 1272 表达式求值
- NYOJ-1272 表达式求值
- nyoj 1272 表达式求值--河南省第九届省赛A题
- NYOJ 1272:表达式求值(2016河南省ACM-A)
- NYOJ1272表达式求值(2)
- nyoj 1272 表达式求值