#include<bits/stdc++.h>
using namespace std;
stack<int>num;
stack<char>op;
void eval(){
int b=num.top();num.pop();
int a=num.top();num.pop();
char c=op.top();op.pop();
int x;
if(c=='+')x=a+b;
else if(c=='-')x=a-b;
else if(c=='x')x=a*b;
else{
if(a*b>=0)x=a/b;
else{
if(a%b==0)x=a/b;
else x=a/b-1;
}
}
num.push(x);
}
int main(){
unordered_map<char,int>pr;
pr['+']=pr['-']=1;
pr['x']=pr['/']=2;
int n;
cin>>n;
while(n--){
string str;
cin>>str;
num=stack<int>();
op=stack<char>();
for(auto c:str)
if(c>='1'&&c<='9')num.push(c-'0');
else{
while(op.size()&&pr[op.top()]>=pr[c])eval();
op.push(c);
}
while(op.size())eval();
if(num.top()==24)puts("Yes");
else puts("No");
}
return 0;
}
第二次复习
#include<bits/stdc++.h>
using namespace std;
map<char,int>mp;
int al(char t,stack<int>&num,stack<char>&op){
int k1=num.top();num.pop();
int k2=num.top();num.pop();
if(t=='+')return k1+k2;
if(t=='-')return k2-k1;
if(t=='x')return k1*k2;
if(t=='/')return k2/k1;
}
void oper(string str,stack<int>num,stack<char>op){
for(auto t:str){
if(t>='0'&&t<='9'){
num.push(t-'0');
}else{
if(!op.empty()){
if(mp[t]<=mp[op.top()]){
int m=al(op.top(),num,op);
op.pop();
op.push(t);
num.push(m);
}else{
op.push(t);
}
}else op.push(t);
}
}
while(!op.empty()){
int k1=num.top();num.pop();
int k2=num.top();num.pop();
int k=0;
char t=op.top();op.pop();
if(t=='+')k=k1+k2;
if(t=='-')k=k2-k1;
if(t=='x')k=k1*k2;
if(t=='/')k=k2/k1;
num.push(k);
}
if(num.top()==24)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
int main(){
mp['-']=mp['+']=1;
mp['x']=mp['/']=2;
int n;
cin>>n;
while(n--){
string str;
stack<int>num;
stack<char>op;
cin>>str;
oper(str,num,op);
}
}