CCF 二十四点

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-23 05:57   198   0

原题链接

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int main() {
    int n,ans,a,b;
    char ch;
    char s[10];
    stack<char>st,st2;
    stack<int>temp,temp2;
    cin >> n;
    for(int i=0; i<n; i++) {
        cin >> s;
        while(!st.empty()) st.pop();
        while(!temp.empty()) temp.pop();
        while(!st2.empty()) st2.pop();
        while(!temp2.empty()) temp2.pop();
        for(int j=0; j<7; j++) {
            if(s[j]<='9' && s[j]>='0')temp.push(s[j]-'0');//数字和+-全部入栈
            else if(s[j]=='+' || s[j]=='-') {
                st.push(s[j]);
            } else if(s[j]=='x' || s[j]=='/') {    // 乘除直接计算
                a = temp.top();
                temp.pop();
                b = s[j+1] - '0';
                temp.push(s[j]=='x' ? a*b : a/b);
                j++;    // 在计算乘除的时候,已经把下一个数字用了
            }
        }
        // 目的是把操作顺序改过来
        while(!st.empty()) {
            st2.push(st.top());
            st.pop();
        }
        while(!temp.empty()) {
            temp2.push(temp.top());
            temp.pop();
        }
        while(!st2.empty()) {
            ch = st2.top();
            st2.pop();
            a = temp2.top();
            temp2.pop();
            b = temp2.top();
            temp2.pop();
            temp2.push(ch == '+' ? a + b : a-b);
        }
        ans = temp2.top();
        if(ans == 24) cout<< "Yes" <<endl;
        else cout<< "No"<<endl;
    } 
    return 0;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP