Fork me on github

CCF-CSP题解 201903-2 二十四点

可枚举。

写栈的主要思想是:一个数栈\(numSta\),一个运算符栈\(opSta\)。遇到一个运算符,就把之前优先级\(equal\ or\ greater\ than\)它的运算符处理掉。

#include <bits/stdc++.h>

using namespace std;

int operation(int num1, char op, int num2)
{
    if (op == '+')
        return num1 + num2;
    else if (op == '-')
        return num1 - num2;
    else if (op == 'x')
        return num1 * num2;
    else
        return num1 / num2;
}

int getAns(char s[]) {
    stack<int> numSta;
    stack<char> opSta;
    for (int i = 1; i <= 7; i++)
    {
        if (s[i] >= '1' && s[i] <= '9')
            numSta.push(s[i] - '0');
        else
        {
            if (s[i] == '+' || s[i] == '-')
            {
                while (!opSta.empty())
                {
                    char op = opSta.top(); opSta.pop();
                    int num2 = numSta.top(); numSta.pop();
                    int num1 = numSta.top(); numSta.pop();
                    numSta.push(operation(num1, op, num2));
                }
                opSta.push(s[i]);
            }
            else
            {
                while (!opSta.empty() && (opSta.top() == 'x' || opSta.top() == '/'))
                {
                    char op = opSta.top(); opSta.pop();
                    int num2 = numSta.top(); numSta.pop();
                    int num1 = numSta.top(); numSta.pop();
                    numSta.push(operation(num1, op, num2));
                }
                opSta.push(s[i]);
            }
        }
    }
    while (!opSta.empty())
    {
        char op = opSta.top(); opSta.pop();
        int num2 = numSta.top(); numSta.pop();
        int num1 = numSta.top(); numSta.pop();
        numSta.push(operation(num1, op, num2));
    }
    return numSta.top();
}

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

    while (n--)
    {
        char s[10];
        scanf("%s", s + 1);
        if (getAns(s) == 24)
            printf("Yes\n");
        else
            printf("No\n");
    }

    return 0;
}

posted @ 2019-08-14 15:32  acboyty  阅读(601)  评论(0编辑  收藏  举报