• [UPC] Postfix Evaluation 后缀表达式求值 | 栈的简单应用


    题目描述

    In a postfix expression, operators follow their operands. For example, [ 5 2 * ] is interpreted as 5 * 2. If there are multiple operators, each operator appears after its last operand. Here are more examples, showing how postfix compares to parenthesized expressions:
    6   3 + 5 ∗ 2 − 6 3 + 5 * 2 − 6 3+52 等同 ( ( 6 + 3 ) ∗ 5 ) – 2 ) ((6 + 3) * 5) – 2) ((6+3)5)2)

    4   3   2 ∗ + 4 3 2 * + 4 3 2+ 等同 4 + ( 3 ∗ 2 ) 4 + (3 * 2) 4+(32)
    These examples show that the operand affected by an operator can be the result of a previous calculation.
    Here is what you need to do: Given an integer postfix expression, you must calculate and print its value.

    输入

    Each input will consist of a single test case. Your program will be run multiple times on different inputs.
    A single input line will contain a postfix expression containing single digit integers and operators from the following set: { +, –, /, * } (add, subtract, divide, multiply). There will be a single space between each digit and and operator. The line will contain no more than 64 operators and numbers, total.

    输出

    Output will be a single integer on a line by itself.
    样例输入 Copy

    【样例16 3 + 5 * 2 –
    【样例26 3 + 5 2 * *
    【样例34 3 2 * + 
    

    样例输出 Copy

    【样例143
    【样例290
    【样例310
    
    stack<ll> st;
    int main() {
    	char c;
    	while(cin >> c) {
    		if(isdigit(c)){
    			st.push(c - '0');
    		}else{
    			ll a = st.top();
    			st.pop();
    			ll b = st.top();
    			st.pop();
    			if(c == '+') st.push(a + b);
    			else if(c == '-') st.push(b - a);
    			else if(c == '*') st.push(a * b);
    			else st.push(b / a);
    		}
    	}
    	cout << st.top() << endl;
    	return 0;
    }
    /**
    
    
    **/
    
    
  • 相关阅读:
    cf D. Vessels
    cf C. Hamburgers
    zoj 3758 Singles' Day
    zoj 3777 Problem Arrangement
    zoj 3778 Talented Chef
    hdu 5087 Revenge of LIS II
    zoj 3785 What day is that day?
    zoj 3787 Access System
    判断给定图是否存在合法拓扑排序
    树-堆结构练习——合并果子之哈夫曼树
  • 原文地址:https://www.cnblogs.com/PushyTao/p/15459789.html
Copyright © 2020-2023  润新知