zoukankan      html  css  js  c++  java
  • 洛谷P1449后缀表达式(读题模拟,栈)

    题目链接:https://www.luogu.org/problemnew/show/P1449

    这道题的难点就在读题,把题读明白是干什么的,理解题目意思样例意思。

    读懂之后就好说了,用栈即可,一个注意事项是:数可能有多位,所以要往前找,也用栈存起来好做。

     1 #include <iostream>
     2 #include <string>
     3 #include <algorithm>
     4 #include <iomanip>
     5 #include <stack>
     6 #include <cstdio>
     7 #include <cstring>
     8 #include <cmath>
     9 using namespace std;
    10 typedef long long ll;
    11 typedef unsigned long long ull;
    12 const int maxn=1e6+5;
    13 char a[maxn];
    14 stack<int> sta;
    15 stack<char> S;
    16 
    17 int main()
    18 {
    19     ios::sync_with_stdio(false); cin.tie(0);
    20 
    21     cin>>a;
    22 
    23     int len=strlen(a);
    24     int lasrd=-1;
    25     for(int i=0;i<=len-1;i++)
    26     {
    27         if(a[i]=='.')//存数,找数字
    28         {
    29             for(int j=i-1;j>=0;j--)
    30             {
    31                 if(a[j]>='0' && a[j]<='9')
    32                 {
    33                     S.push(a[j]);
    34                 }
    35                 else break;
    36             }
    37             int x=0;
    38             while(S.size())
    39             {
    40                 int t=S.top(); S.pop();
    41                 x=x*10+t-48;
    42             }
    43 
    44             sta.push(x);
    45         }
    46         else if(a[i]=='+' || a[i]=='-' || a[i]=='*' || a[i]=='/')//运算符计算
    47         {
    48             int x=sta.top(); sta.pop();
    49             int y=sta.top(); sta.pop();
    50             int h=0;
    51             if(a[i]=='+') h=y+x;
    52             else if(a[i]=='-') h=y-x;//注意是y-x,不是x-y,因为是逆序存的
    53             else if(a[i]=='*') h=y*x;
    54             else if(a[i]=='/') h=y/x;
    55             sta.push(h);
    56         }
    57     }
    58 
    59     cout<<sta.top()<<endl;
    60 
    61     return 0;
    62 }

    完。

  • 相关阅读:
    4. Qt的容器类
    hdu 4507 数位dp(求和,求平方和)
    MVC3和MVC4中CRUD操作
    SSL 中证书能否够使用IP而不是域名
    TinyXml快速入门(一)
    C++ TinyXml操作(含源码下载)
    Tinyxml 操作XML
    msxml 操作xml
    MFC中全局变量的定义及使用
    VC++中操作XMLWin32实例
  • 原文地址:https://www.cnblogs.com/redblackk/p/9796422.html
Copyright © 2011-2022 走看看