HDu 1237(アナログスタック、水題)

11148 ワード

タイトルリンク: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             }else

66                 SS.push(x1-x2);

67         }

68         printf("%.2lf
",SS.top()); 69 } 70 return 0; 71 }