洛谷 P1449 后缀表达式 Label:表达式计算系列

题目描述

所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。

输入输出格式

输入格式:

输入:后缀表达式

输出格式:

输出:表达式的值

输入输出样例

输入样例#1:
3.5.2.-*7.+@
输出样例#1:
16

说明

字符串长度,1000内。

代码


 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #define ll long long 
 6 using namespace std;
 7 ll num[1005];
 8 string str;
 9 
10 void cul(ll p,ll op){
11     if(op==0) num[p-1]=num[p-1]+num[p];
12     if(op==1) num[p-1]=num[p-1]-num[p];
13     if(op==2) num[p-1]=num[p-1]*num[p];
14     if(op==3) num[p-1]=num[p-1]/num[p];
15 }
16 
17 ll result(){
18     ll op_nxt;
19     ll len=str.length(),p=-1;
20     ll num_nxt=0;
21     for(int i=0;i<len;i++){
22         if(str[i]>='0'&&str[i]<='9') num_nxt=num_nxt*10+(str[i]-'0');
23         else if(str[i]=='.'){
24             num[++p]=num_nxt;
25             num_nxt=0;
26         }
27         else{
28             
29             if(str[i]=='+') op_nxt=0;
30             if(str[i]=='-') op_nxt=1;
31             if(str[i]=='*') op_nxt=2;
32             if(str[i]=='/') op_nxt=3;
33             
34             cul(p--,op_nxt);
35         }
36     }
37     return num[0];
38 }
39 int main(){
40 //    freopen("01.in","r",stdin);
41     cin>>str;
42     printf("%lld
",result());
43     return 0;
44 }
View Code

参见这里

http://www.cnblogs.com/radiumlrb/p/5759319.html

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
原文地址:https://www.cnblogs.com/radiumlrb/p/5836422.html