[CCF CSP]二十四点2019-3-2

题目链接:http://118.190.20.162/view.page?gpid=T88

思路:后缀表达式求值

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <queue>
#include <map>
using namespace std;
string str;
int n;
queue<char> Back;
stack<char> tmp;
stack<int> number;
map<char,int> priority;
bool res[100+10];
int main() {
    cin>>n;
    priority['+']=1;priority['-']=1;priority['x']=2;priority['/']=2;
    for(int i=0;i<n;i++){
        string str;
        cin>>str;
        int sum=0;
        for(int j=0;j<str.size();j++){
                if(str[j]>='0'&&str[j]<='9'){
                    Back.push(str[j]);
                }
                else
                {
                    if(!tmp.empty()&&priority[str[j]]>priority[tmp.top()]){
                        tmp.push(str[j]);
                    }
                    else
                    {
                        while(!tmp.empty()&&priority[tmp.top()]>=priority[str[j]]){
                            char c=tmp.top();
                            Back.push(c);
                            tmp.pop();
                        }
                        tmp.push(str[j]);
                    }
                }
        }
        while(!tmp.empty()){
            char c=tmp.top();
            Back.push(c);
            tmp.pop();
        }
        while(!Back.empty()){
            char c=Back.front();
            Back.pop();
            if(c>='0'&&c<='9'){
                number.push(c-'0');
            }
            else
            {
                int a=number.top();
                number.pop();
                int b=number.top();
                number.pop();
                if(c=='+'){
                    sum=a+b;
                    number.push(sum);
                }
                else if(c=='-'){
                    sum=b-a;
                    number.push(sum);
                }
                else if(c=='x'){
                    sum=a*b;
                    number.push(sum);
                }
                else if(c=='/'){
                    sum=b/a;
                    number.push(sum);
                }
            }
        }
        if(number.top()==24)
            res[i]=1;
        else
            res[i]=0;
    }
    for(int i=0;i<n;i++){
        if(res[i])
            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、付费专栏及课程。

余额充值