NOIP2013 表达式求值

本文探讨了利用栈解决数学表达式求值的问题,通过构建两个栈,一个用于存储数字,另一个用于存储运算符,实现了对优先级较低的运算符进行计算,最终得到表达式的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:http://www.luogu.org/problem/show?pid=1981#
分析:栈的应用。两个栈,一个存数字一个存操作符,当遇到符号时计算优先级比它小的所有符号,则最后栈顶元素即为答案。
代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
const int Tmax=105,MOD=10000;
stack<int> Snum,Sopt;
void clear(int num)
{
    int tmp1,tmp2,opt;
    while(!Sopt.empty())
    {
        if(Sopt.top()<=num)
        {
            opt=Sopt.top();
            Sopt.pop();
            tmp1=Snum.top();
            Snum.pop();
            tmp2=Snum.top();
            Snum.pop();
            if(opt==2) Snum.push((tmp1+tmp2)%MOD);
            else Snum.push((tmp1*tmp2)%MOD);
        }
        else break;
    }
    return;
}
int main()
{
    int num=0;
    char ch;
    while(scanf("%c",&ch)==1&&ch!='\n')
    {
        if(ch=='+'){
            Snum.push(num);
            clear(2);
            Sopt.push(2);
            num=0;
        }
        else if(ch=='*'){
            Snum.push(num);
            clear(1);
            Sopt.push(1);
            num=0;
        }
        else num=(num*10+ch-'0')%MOD;
    }
    Snum.push(num);
    clear(3);
    printf("%d",Snum.top());
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值