判断两个表达式在数学上是否是等价的。
输入:
第一行:N(1<=N<=20),表示测试数据组数。
接下来每组测试数据包括两行,每行包括一个数学表达式,每个表达式的长度不超过80个字符。输入数据没有空行。
一个表达式可能包括:
单个英文字母表示的变量(区分大小写)
数字(只有一位数)
配对的括号
运算符加+、减-、乘*
任意数量的空格或tab(可能出现在表达式中间的任何位置)
注意:表达式保证是语法正确的,且所有运算符的优先级相同,运算次序从左至右。变量的系数和指数保证不超过16位整数。
输出
对每个测试数据,输出一行:等价则输出“YES”,不等价则输出“NO”。
计算表达式有两种形式:
1、两个操作数+一个操作符。
2、一个操作符+两个操作数。
情况一的例子:
对二叉树后序遍历:abcd-*+ef/- 一般用后序遍历。
先序遍历:-+a*b-cd/ef,与后序遍历相似,从后往前计算。
中序遍历:a+b(c-d)-e/f*,可知中序遍历为表达式形式,但是用C语言没有办法计算
样例输入:
3
(a+b-c)*2
(a+a)+(b*2)-(3*c)+c
a*2-(a+c)+((a+c+e)*2)
3*a+c+(2*e)
(a-b)*(a-b)
(a*a)-(2*a*b)-(b*b)
样例输出:
YES
YES
NO
代码实现:
#include <iostream>
#include <stack>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
//后序遍历:
string chang(char *str)
{
stack<char> s;
int len=strlen(str);
int i;
string st="";
for(i=0; i<len; i++)
{
if(str[i]>='a'&&str[i]<='z')
st=st+str[i];
else if(str[i]>='A'&&str[i]<='Z')
st=st+str[i];
else if(str[i]>='0'&&str[i]<='9')
st=st+str[i];
else if(str[i]=='(')
s.push(str[i]);
else if(str[i]==')')
{
while(s.top()!='(')
{
st=st+s.top();
s.pop();
}
s.pop();
}
else if(str[i]=='+'||str[i]=='-')
{
while(!s.empty()&&s.top()!='(')
{
st=st+s.top();
s.pop();
}
s.push(str[i]);
}
else if(str[i]=='*')
{
while(!s.empty()&&s.top()!='('&&s.top()=='*')
{
st=st+s.top();
s.pop();
}
s.push(str[i]);
}
else if(str[i]==' '||str[i]=='\t')
continue;
}
while(!s.empty())
{
st=st+s.top();
s.pop();
}
return st;
}
//用字符的编码来求值,字符ab...直接转换成int数据类型。
int get(string str)
{
int len=str.size();
int i,d,t;
stack<int> s;
for(i=0; i<len; i++)
{
if(str[i]>='a'&&str[i]<='z')
{
d=str[i];
s.push(d);
}
else if(str[i]>='A'&&str[i]<='Z')
{
d=str[i];
s.push(d);
}
else if(str[i]>='0'&&str[i]<='9')
{
d=str[i]-'0'; //注意这里不能再用字符的编码来计算了,要转换成相应的整数
s.push(d);
}
else if(str[i]=='+')
{
d=s.top();
s.pop();
t=s.top();
s.pop();
s.push(d+t);
}
else if(str[i]=='-')
{
d=s.top();
s.pop();
t=s.top();
s.pop();
s.push(t-d);
}
else if(str[i]=='*')
{
d=s.top();
s.pop();
t=s.top();
s.pop();
s.push(d*t);
}
}
t=s.top();
s.pop();
return t;
}
int main()
{
int n,i;
cin>>n;
getchar();
for(i=0;i<n;i++)
{
char stra[100],strb[100];
cin.getline(stra, 100);
string str1=chang(stra);
int x1=get(str1);
cin.getline(strb, 100);
string str2=chang(strb);
int x2=get(str2);
if(x1==x2)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}