hdu 1237(模拟栈、水题)

来源:互联网 发布:安卓数据库 编辑:程序博客网 时间:2024/05/18 13:45

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237

思路:模拟栈,先处理*和/的,算出结果后在入栈,将‘+’和‘-’入s栈,最后由于考虑加减运算符的优先级,还有倒一下栈。。这样就一共用到了4个栈。。。

View Code
 1 #define _CRT_SECURE_NO_WARNINGS 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 #include<stack> 7 using namespace std; 8  9 int main(){10     char str[222];11     while(gets(str),strcmp(str,"0")){12         int len=strlen(str);13         stack<double>S,SS;14         stack<char>s,ss;15         for(int i=0;i<len;i++){16             if(str[i]==' ')continue;17             else if(str[i]=='*'||str[i]=='/'){18                 double x=S.top();19                 S.pop();20                 int j;21                 double y=0;22                 for(j=i+2;j<len;j++){23                     if(str[j]!=' '){24                         y=y*10+str[j]-'0';25                     }else 26                         break;27                 }28                 if(str[i]=='*')S.push(x*y);29                 else S.push(x/y);30                 i=j;31             }else if(str[i]=='+'||str[i]=='-'){32                 s.push(str[i]);33             }else {34                 int j;35                 double x=0;36                 for(j=i;j<len;j++){37                     if(str[j]!=' '){38                         x=x*10+str[j]-'0';39                     }else 40                         break;41                 }42                 S.push(x);43                 i=j;44             }45         }46         while(!S.empty()){47             double x=S.top();48             SS.push(x);49             S.pop();50         }51         while(!s.empty()){52             char ch=s.top();53             ss.push(ch);54             s.pop();55         }56         while(!SS.empty()&&!ss.empty()){57             double x1=SS.top();58             SS.pop();59             double x2=SS.top();60             SS.pop();61             char ch=ss.top();62             ss.pop();63             if(ch=='+'){64                 SS.push(x1+x2);65             }else66                 SS.push(x1-x2);67         }68         printf("%.2lf\n",SS.top());69     }70     return 0;71 }

 

0 0
原创粉丝点击