AcWing 3273. 二十四点
原题链接
中等
作者:
Value
,
2021-04-10 08:39:51
,
所有人可见
,
阅读 494
#include <iostream>
#include <cstdio>
#include <stack>
#include <map>
using namespace std;
typedef long long ll;
stack<int> num;
stack<char> op;
map<char, int> piority;
ll res;
void init(){
piority['-'] = 1;
piority['+'] = 1;
piority['/'] = 2;
piority['x'] = 2;
}
int work(int x, int y, char t){
int all = 0;
if(t == '-') all = x - y;
else if(t == '+') all = x + y;
else if(t == '/') all = x / y;
else all = x * y;
return all;
}
int main(){
init();
int n; cin >> n;
while(n -- ){
string s; cin >> s;
for(int i = 0; i < s.size(); i ++ ){
if(s[i] >= '0' && s[i] <= '9') num.push(s[i] - '0');
else{
if(op.empty() || piority[op.top()] < piority[s[i]]) op.push(s[i]);
else{
int num1 = num.top();
num.pop();
int num2 = num.top();
num.pop();
num.push(work(num2, num1, op.top()));
op.pop();
op.push(s[i]);
}
}
}
while(!op.empty()){
int num1 = num.top();
num.pop();
int num2 = num.top();
num.pop();
num.push(work(num2, num1, op.top()));
op.pop();
}
cout << (num.top() == 24 ? "Yes" : "No") << endl;
num.pop();
}
return 0;
}