CCF201903-2 二十四点

/***
根据表达式求值双栈算法编写。
不是最简方法。
思路:map用于存储符号优先级,s是符号栈,res是操作数栈
计算函数写的很不好,重复代码很多
遇到了坑
**/
#include <iostream>
#include <algorithm>
#include <map>
#include<stack>
//#define debug
using namespace std;

map<char , int > m;
stack <char> s;
stack <int> res;

bool f(string& a){
    char op ;
    int sum = 0;
    for(int i = 0;i < a.length() ;i++){
        if(i % 2 == 0){
            res.push(a[i] - '0');
        }else{
            if(!s.empty()){
                op = s.top();
                //s.pop();坑1:在这直接pop了。应该是先比较优先级再pop。
                //即:若栈顶操作符优先级大于当前操作符,则计算值并出栈运算符

                while(m[a[i]] <= m[op] ){
                    s.pop();//坑1的解:该在这里出栈
                    int s1 = res.top();
                    res.pop();
                    int s2 = res.top();
                    res.pop();
                    if(op == '+'){
                       res.push(s1 + s2);
                    }else if(op == '-'){
                        res.push(s2-s1);
                    }else if(op == 'x'){
                        res.push(s1 * s2);
                    }else{
                        res.push(s2 / s1);
                    }
                    if(s.empty())
                       break;
                    op = s.top();
                   // s.pop();//坑1:这句也不能要了
                }
                s.push(a[i]);
            }else{
                s.push(a[i]);
            }
        }
    }
    while(!s.empty()){//坑2:没有计算栈中剩余的运算符。
        op = s.top();
        s.pop();

        int s1 = res.top();
        res.pop();
        int s2 = res.top();
        res.pop();
        if(op == '+'){
           res.push(s1 + s2);
        }else if(op == '-'){
            res.push(s2-s1);
        }else if(op == 'x'){
            res.push(s1 * s2);
        }else{
            res.push(s2 / s1);
        }

    }
    sum = res.top();
    return sum== 24;
}
int main(){
    int n,i,k,j,L,t;
  /*  m.insert('+',1);
    m.insert('-',1);
    m.insert('*',2);
    m.insert('/',2);*/
    m['+'] = 1;
    m['-'] = 1;
    m['x'] = 2;
    m['/'] = 2;
    string a;
    cin >> n;

    for(i= 0;i < n;i++){
        cin >>a;
        if(f(a))
            a = "Yes";
        else
            a = "No";
        cout << a << endl;
    }


  return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值