洛谷 P1981:[NOIP 2013 普及组 T2] 表达式求值 ← 栈

【题目来源】
https://www.luogu.com.cn/problem/P1981

【题目描述】
给定一个只包含加法和乘法的算术表达式,请你编程计算表达式的值。

【输入格式】
一行,为需要你计算的表达式,表达式中只包含数字、加法运算符 + 和乘法运算符 *,且没有括号,所有参与运算的数字均为 0 到 2^31-1 之间的整数。
输入数据保证这一行只有 0123456789+* 这 12 种字符。

【输出格式】
一个整数,表示这个表达式的值。
注意:当答案长度多于 4 位时,请只输出最后 4 位,前导 0 不输出。

【输入样例】
1+1234567890*1

【输出样例】
7891

【数据范围】
对于 30% 的数据,0≤表达式中加法运算符和乘法运算符的总数≤100。
对于 80% 的数据,0≤表达式中加法运算符和乘法运算符的总数≤1000。
对于 100% 的数据,0≤表达式中加法运算符和乘法运算符的总数≤100000。

【算法分析】
分别给出使用栈,及不用栈的两种代码。

【算法代码:栈】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MOD=10000;

int main() {
    string s;
    cin>>s;
    s+='+';

    stack<LL> stk;
    LL num=0;
    char op='+';

    for(char ch:s) {
        if(ch>='0' && ch<='9') {
            num=(num*10+(ch-'0'))%MOD;
        } else {
            if(op=='+') stk.push(num);
            else {
                LL top=stk.top();
                stk.pop();
                stk.push(top*num%MOD);
            }
            op=ch;
            num=0;
        }
    }

    LL ans=0;
    while(!stk.empty()) {
        ans=(ans+stk.top())%MOD;
        stk.pop();
    }
    cout<<ans<<endl;

    return 0;
}

/*
in:
1+1234567890*1

out:
7891
*/

【算法代码二:不用栈】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MOD=10000;

int main() {
    string s;
    cin>>s;
    s+='+';

    LL ans=0, t=0, num=0;
    char op='+';

    for(char ch:s) {
        if(ch>='0' && ch<='9') {
            num=(num*10+(ch-'0'))%MOD;
        } else {
            if(op=='+') {
                ans=(ans+t)%MOD;
                t=num;
            } else t=t*num%MOD;
            op=ch;
            num=0;
        }
    }
    cout<<(ans+t)%MOD<<endl;

    return 0;
}

/*
in:
1+1234567890*1

out:
7891
*/

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/149981270
https://blog.csdn.net/hnjzsyjyj/article/details/171820221
https://blog.csdn.net/hnjzsyjyj/article/details/148987127
https://blog.csdn.net/hnjzsyjyj/article/details/171820606

相关推荐
zh_xuan1 个月前
LeeCode 496. 下一个更大元素I
数据结构·算法·栈·单调栈
布莱克6051 个月前
C++ 中堆和栈的区别详解
开发语言·c++·栈·堆
无忧.芙桃2 个月前
C++语言原理与实践(十三):stack、queue 和 priority_queue的介绍与使用
开发语言·c++·栈·队列
啵啵啵鱼2 个月前
第三章 栈、队列和数组相关结构
java·数据结构·栈·队列
Jasmine_llq2 个月前
《P17461 [GESP202609 八级] 生成树计数》
算法·栈·tarjan 算法·边双连通分量·深度优先搜索 dfs·tarjan 保存当前路径节点·模乘法
闻缺陷则喜何志丹3 个月前
【栈 运算系统】P3719 [AHOI2017初中组] rexp|普及+
c++·算法·栈·洛谷·运算系统
我不会起名字3223 个月前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·栈
布莱克6053 个月前
栈(Stack)详解:定义、作用、应用场景及与队列的区别(附 C/C++ 代码)
c语言·开发语言·c++·栈
桃蹊、3 个月前
FreeRTOS(二)之堆和栈:内存基础入门
freertos·内存管理·栈·堆