可以纯暴力做,也可以直接中缀做
这里采用中缀转后缀,用逆波兰式求解,这里是写了完整的中缀转后缀过程,实际这道题只需要其中一部分,代码写的比较垃圾懒得改了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
int cmp(char a, char b)
{
int anum; //栈内
int bnum; //栈外
if (a == '#')
anum = 0;
else if (a == '(')
anum = 1;
else if (a == '^')
anum = 6;
else if (a == 'x' || a == '/')
anum = 5;
else if (a == '+' || a == '-')
anum = 3;
else if (a == ')')
anum = 8;
if (b == '#')
bnum = 0;
else if (b == '(')
bnum = 8;
else if (b == '^')
bnum = 7;
else if (b == 'x' || b == '/')
bnum = 4;
else if (b == '+' || b == '-')
bnum = 2;
else if (b == ')')
bnum = 1;
if (anum > bnum)
return 1;
else if (anum == bnum)
return 2;
else
return 3;
}
int main()
{
//48-57
int num;
cin >> num;
while (num--)
{
char a[10];
stack<char> aa;
stack<char> re;
stack<char> b;
stack<int> bb;
scanf("%s", a);
int len = strlen(a);
a[len] = '#';
aa.push('#');
for (int i = 0; i <= len; i++)
{
if (a[i] <= 57 && a[i] >= 48)
re.push(a[i]);
else
while (!aa.empty())
{
int t = cmp(aa.top(), a[i]);
if (t == 3)
{
aa.push(a[i]);
break;
}
else if (t == 2)
{
aa.pop();
break;
}
else if (t == 1)
{
char temp = aa.top();
re.push(temp);
aa.pop();
continue;
}
}
}
while (!re.empty())
{
char temp = re.top();
b.push(temp);
re.pop();
}
while (!b.empty())
{
if (b.top() <= 57 && b.top() >= 48)
{
int temp = b.top() - '0';
bb.push(temp);
b.pop();
}
else
{
int count1 = bb.top();
bb.pop();
int count2 = bb.top();
bb.pop();
if (b.top() == '+')
bb.push(count1 + count2);
if (b.top() == '-')
bb.push(count2 - count1);
if (b.top() == 'x')
bb.push(count1 * count2);
if (b.top() == '/')
bb.push(count2 / count1);
b.pop();
}
}
if (bb.top() == 24)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}