[CCF/CSP] 2019-(2) 二十四点 C++ 100分

试题名称代码长度编程语言评测结果得分时间使用空间使用
二十四点1.778KBC++正确10015ms528.0KB

关键点:

1. 中缀表达式转为前缀(或后缀)表达式,此题不考虑“(”  “)”,所以比较简单。

2. 处理字符时,注意区别应该是char类型还是int类型。

3. 运算符的优先级可以用map。

#include <stdio.h>
#include <iostream>
#include <stack>
#include <map>
using namespace std;

map<char, int> priority;

int main(){
    priority['+'] = 1;
    priority['-'] = 1;
    priority['x'] = 2;
    priority['/'] = 2;

    //freopen("201903-2-24.txt","r", stdin);

    int n;
    scanf("%d", &n);

    char line[8], pre[8];
    for(int i=0; i<n; ++i){
        scanf("%s", line);
        stack<char> s1, s2;
        char tmp;
        for(int j=6; j>=0; --j){
            tmp = line[j];
            if(tmp>='0' && tmp<='9'){
                s2.push(tmp);
            }else{
                while( !s1.empty() && priority[tmp] < priority[s1.top()]){
                    s2.push(s1.top());
                    s1.pop();
                }
                if(s1.empty() || priority[tmp] >= priority[s1.top()])
                    s1.push(tmp);
            }
        }
        while(!s1.empty()){
            s2.push(s1.top());
            s1.pop();
        }
        int m = 0;
        while(!s2.empty()){
            pre[m++] = s2.top();
            s2.pop();
        }


        int ans;
        stack<int> s3;
        for(int j=6; j>=0; --j){
            char tmp = pre[j];
            if(tmp >= '0' && tmp <= '9'){
                s3.push(tmp-'0');
            }else{
                int c1 = s3.top();
                s3.pop();
                int c2 = s3.top();
                s3.pop();

                if(tmp == '+'){
                    ans = c1 + c2;
                }else if(tmp == '-'){
                    ans = c1 - c2;
                }else if(tmp == 'x'){
                    ans = c1 * c2;
                }else{
                    ans = c1 / c2;
                }
                s3.push(ans);
            }
        }
        if(ans == 24){
            printf("Yes\n");
        }else{
            printf("No\n");
        }

    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值