[CCF] 201903-2 二十四点 Apaer_xzc
[CCF] 201903-2 二十四点
题面
思路:计算中缀表达式,然后判断24即可
我的代码
//CCF 201903-2 二十四点
#include <bits/stdc++.h>
using namespace std;
char str[10],in[20];
int a[10];
int super(char ch)
{
if(ch=='+'||ch=='-') return 2;
if(ch=='x'||ch=='/'||ch=='*') return 3;
if(ch=='#') return 0;
return -1;
}
int cal(int x,int y,char op)
{
if(op=='+') return x+y;
else if(op=='-') return x-y;
else if(op=='/') return x/y;
else return x*y;
}
void solve()
{
stack<int> num;
stack<char> alp;
alp.push('#');
for(int i=0;i<7;++i)
{
if(isdigit(in[i]))
{
num.push(in[i]-'0');
}
else
{
char now = in[i];
while(super(now)<=super(alp.top()))
{
char tp = alp.top(); alp.pop();
int right = num.top(); num.pop();
int left = num.top(); num.pop();
num.push(cal(left,right,tp));
}
alp.push(now);
}
}
while(!alp.empty()&&alp.top()!='#')
{
char tp = alp.top();
alp.pop();
int right = num.top();num.pop();
int left = num.top();num.pop();
num.push(cal(left,right,tp));
}
if(num.top()==24) puts("Yes");
else puts("No");
}
int main()
{
int T;cin>>T;
while(T--)
{
scanf("%s",in);
solve();
}
return 0;
}