• 洛谷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 }

    完。

  • 相关阅读:
    JS和C#对Json的操作
    JS图形化插件利器组件系列 —— Gojs组件
    Android APK反编译 apktool使用教程
    UML系列图
    多线程学习 ---- 系列教程
    大型网站架构之系列
    经典算法题锦集
    基本算法系列15天速成
    居转户--相关信息
    使用C#创建Windows服务
  • 原文地址:https://www.cnblogs.com/redblackk/p/9796422.html
Copyright © 2020-2023  润新知