CSP 201903-2 二十四点(简单模拟)

 

 输入:

10
9+3+4*3
5+4*5*5
7-9-9+8
5*6/5*4
3+5+7+9
1*1+9-9
1*9-5/9
8/5+6*9
6*7-3*6
6*4+4/5

 提示:1.把 - 号后面的数字变成相应的负数,再把 - 号变成 + 号(所以只剩+、/、x)

            2.设一个数据栈,按顺序遍历表达式,第一个数字直接入栈,后面的数字如果前面的运算符是+,直接入栈,否则取出栈顶数字与该数字进行 x或/运算,将运算结果入栈 。最后顺序遍历数据栈求和即可

            3.WA到心态爆炸的!!!!老老实实的看题目做,乘法是x而不是*

#include <iostream>
#include <stack>
using namespace std;

int main()
{
    int n;
    int a[4];
    char b[3];
    cin >> n;
    while(n--) {
        string ss;
        cin >> ss;
        for(int i = 0; i < ss.length(); i++) {
            if(i % 2 == 0) {
                a[i/2] = ss[i] - '0';
                if(ss[i-1] == '-') a[i/2] = -a[i/2];//如果前面的符号是-,该数变成对应的负数
            } else {
                b[(i-1)/2] = ss[i];
            }

        }
        for(int i = 0; i < 3; i++) {//将-改为+
            if(b[i] == '-') b[i] = '+';
        }
        stack<int>s;
        for(int i = 0; i < 4; i++) {
            if(i == 0) s.push(a[i]);//第一个元素直接入栈
            else {
                if(b[i-1] == '/') {//前面符号是x、/取出栈顶元素进行计算,结果入栈
                    int temp = s.top();
                    s.pop();
                    temp = temp / a[i];
                    s.push(temp);
                } else if(b[i-1] == 'x') {
                    int temp = s.top();
                    s.pop();
                    temp = temp * a[i];
                    s.push(temp);
                } else {//前面符号是+ 直接入栈
                    s.push(a[i]);
                }
            }
        }
        int sum = 0;
        while(!s.empty()) {
            int temp = s.top();
            s.pop();
            sum += temp;
        }//遍历最后的数据栈求和
        if(sum == 24) cout << "Yes" <<endl;
        else cout << "No" << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LLLAIH/p/11650506.html