先把中缀表达式转换成后缀表达式,题目中已经说了所有算符优先级相等,这里就不用考虑优先级.
然后计算后缀表达式,对每个字符的值取字符表的位置就可以了.
#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
#include <string.h>
using namespace std;
int pri[128];
char buf[128];
long long getVal(){
stack<char> stk;
int i = 0, len = strlen(buf);
string postExp = "";
while(i < len){
char ch = buf[i];
if(isalpha(ch)){
postExp += ch;
}else if(isdigit(ch)){
string tmp = "";
for(; i < len && isdigit(buf[i]);++i)tmp += buf[i];
postExp += " " + tmp + " ";
continue;
}
else if(ch == '('){
stk.push(ch);
}else if(ch == ')'){
while(stk.size()){
char t = stk.top();
stk.pop();
if(t == '(')break;
postExp += t;
}
}else if(ch == '+' || ch == '-' || ch =='*'){
while(stk.size() && stk.top() != '('){
postExp += stk.top();
stk.pop();
}
stk.push(ch);
}
++i;
}
while(stk.size()){
postExp += stk.top();
stk.pop();
}
i = 0;
stack<long long> vs;
while(i < postExp.size()){
char ch = postExp[i];
if(isdigit(ch)){
long long t = ch - '0';
for(++i; i < postExp.size() && isdigit(postExp[i]);++i){
t = t * 10 + (ch -'0');
}
vs.push(t);
continue;
}else if(isalpha(ch)){
vs.push(ch - ('a' - 1));
}else if(ch == '+' || ch == '-' || ch =='*'){
long long op1, op2;
op2 = vs.top();
vs.pop();
op1 = vs.top();
vs.pop();
if(ch == '+')
vs.push(op1 + op2);
else if(ch == '-')
vs.push(op1 - op2);
else if(ch == '*')
vs.push(op1 * op2);
}
++i;
}
return vs.top();
}
int main(){
int T;
scanf("%d\n", &T);
while(T--){
gets(buf);
long long ans1 = getVal();
gets(buf);
long long ans2 = getVal();
if(ans1 == ans2){
printf("YES\n");
}else{
printf("NO\n");
}
}
return 0;
}