zoukankan      html  css  js  c++  java
  • P1449 后缀表达式

    题目描述

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

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

    输入输出格式

    输入格式:

    输入:后缀表达式

    输出格式:

    输出:表达式的值

    输入输出样例

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

    说明

    字符串长度,1000内。

    //打基础
    //以前在书上看过,今天看到一道DP题,
    //暴力分要用表达式树做
    //所以来做一下这道题
    
    //RT模拟,可以想到,要开个栈 
    //遇到数字就加入数字栈中,遇到运算符就把数字栈的顶端两个元素取出来做运算再压进去
    //最后数字栈里剩下的那个数就是ans 
    
    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #include<string>
    #include<stack>
    using namespace std;
    
    char c;
    stack<int> A;
    stack<char> B;
    
    int main()
    {
        int num=0,a,b;
        while(c=getchar())
        {
            if(c=='@')
                break;
            if(isdigit(c))
            {
                num=0;
                while(isdigit(c))
                {
                    num=num*10+c-'0';
                    c=getchar();
                }
                A.push(num);
            }
            else
            {
                b=A.top(),A.pop();
                a=A.top(),A.pop();
                switch(c)
                {
                    case '+':
                        a+=b;break;
                    case '-':
                        a-=b;break;
                    case '*':
                        a*=b;break;
                    default:
                        a/=b;break;
                }
                A.push(a);
            }
        }
        printf("%d",A.top());
        return 0;
    }
  • 相关阅读:
    hlgoj 1766 Cubing
    Reverse Linked List
    String to Integer
    Bitwise AND of Numbers Range
    Best Time to Buy and Sell Stock III
    First Missing Positive
    Permutation Sequence
    Next Permutation
    Gray Code
    Number of Islands
  • 原文地址:https://www.cnblogs.com/lovewhy/p/8682249.html
Copyright © 2011-2022 走看看