CCFCSP-表达式求值-201903-2-二十四点

表达式求值:
一、中缀表达式转为后缀表达式:从头到尾读取中缀表达式的每个对象

  1. 运算数:直接输出
  2. 左括号:压栈(左括号在栈中的优先级最低)
  3. 右括号:将栈顶的运算符弹出并输出直至遇到左括号(出栈,不输出)
  4. 运算符:若优先级大于栈顶运算符时,则把它压栈;
    若优先级小于等于栈顶运算符时,将栈顶运算符弹出并输出;再比较新的栈顶运算符,直到该运算符大于栈顶运算符优先级为止,然后将该运算符压栈;
  5. 若各对象处理完毕,则把堆栈中存留的运算符一并输出。

二、后缀表达式求值:从左到右读入后缀表达式的各项。

  1. 运算数:入栈。
  2. 运算符:从堆栈中弹出适当数量的运算数,计算出结果并入栈。
  3. 栈顶元素为表达式的结果值。

例子:在这里插入图片描述
题目:http://118.190.20.162/view.page?gpid=T88

100分解答:

#include<bits/stdc++.h>
using namespace std;
map<char,int>mp;

int main()
{
    mp['+']=0;mp['-']=0;mp['x']=1;mp['/']=1;
    int n;
    string s;
    cin>>n;
    string postfix="";
    stack<char>st;
    stack<int>ts;
    int a,b;
    for(int i=0;i<n;i++)
    {
        cin>>s;
        postfix="";
        while(!st.empty())
            st.pop();
        for(int j=0;j<7;j++)
        {
            if(s[j]<='9'&&s[j]>='0')
            {
                postfix+=s[j];
            }
            else
            {
                while(!st.empty()&&mp[s[j]]<=mp[st.top()])
                {
                    postfix+=st.top();
                    st.pop();
                }
                st.push(s[j]);

            }
        }
        while(!st.empty())
        {
            postfix+=st.top();
            st.pop();
        }
        //cout<<postfix<<endl;
        while(!ts.empty())
            ts.pop();
        for(int j=0;j<7;j++)
        {
            if(postfix[j]<='9'&&postfix[j]>'0')
            {
                ts.push(postfix[j]-'0');
            }
            else
            {
                b=ts.top();
                ts.pop();
                a=ts.top();
                ts.pop();
                if(postfix[j]=='x')
                    ts.push(a*b);
                else if(postfix[j]=='/')
                    ts.push(a/b);
                else if(postfix[j]=='+')
                    ts.push(a+b);
                else if(postfix[j]=='-')
                    ts.push(a-b);
            }
        }
        //cout<<ts.top()<<endl;
        if(ts.top()==24)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }


    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值