Description
A math instructor is too lazy to grade a question in the exam papers in which students are supposed to produce a complicated formula for the question asked. Students may write correct answers in different forms which makes grading very hard. So, the instructor needs help from computer programmers and you can help.
You are to write a program to read different formulas and determine whether or not they are arithmetically equivalent.
Input
The first line of the input contains an integer N (1 ≤ N ≤ 20) that is the number of test cases. Following the first line, there are two lines for each test case. A test case consists of two arithmetic expressions, each on a separate line with at most 80 characters. There is no blank line in the input. An expression contains one or more of the following:
Single letter variables (case insensitive).
Single digit numbers.
Matched left and right parentheses.
Binary operators +, - and * which are used for addition, subtraction and multiplication respectively.
Arbitrary number of blank or tab characters between above tokens.
Note: Expressions are syntactically correct and evaluated from left to right with equal precedence (priority) for all operators. The coefficients and exponents of the variables are guaranteed to fit in 16-bit integers.
Output
Your program must produce one line for each test case. If input expressions for each test data are arithmetically equivalent, “YES”, otherwise “NO” must be printed as the output of the program. Output should be all in upper-case characters.
Sample Input
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)
Sample Output
YES
YES
NO
题意:每个样例给你两个式子,问两个式子最后的结果是不是一样的。
这个可以用后缀表达式来做。。但我不太会。。
所以就直接递归计算括号中的括号这种情况了。。
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
char ch[100];
char ch1[100];
int work(char ch[],int l,int r)
{
int lnum=0;
int rnum=0;
int lset=0;
int rset=0;
char mark='+';
int ans=0;
for(int i=l;i<=r;i++)
{
if(ch[i]=='+'||ch[i]=='-'||ch[i]=='*')//如果是运算符
{
mark=ch[i];//记录下来
}
if(ch[i]=='(')//如果是括号,寻找右括号
{
lset=i;
lnum++;
while(lnum!=rnum)
{
i++;
if(ch[i]=='(')
{
++lnum;
}
else if(ch[i]==')')
{
++rnum;
}
}
rset=i;
int ans1=work(ch,lset+1,rset-1);//递归计算括号中的括号
if(mark=='+')
ans+=ans1;
if(mark=='-')
ans-=ans1;
if(mark=='*')
ans*=ans1;
}
else if(ch[i]!='+'&&ch[i]!='-'&&ch[i]!='*'&&ch[i]!=' '&&ch[i]!=')')
{
//如果不是括号,则计算
if(ch[i]>='0'&&ch[i]<='9')
ch[i]-='0';
if(mark=='+')
ans+=ch[i];
if(mark=='-')
ans-=ch[i];
if(mark=='*')
ans*=ch[i];
}
}
return ans;
}
int main (void)
{
int t;
cin>>t;
getchar();
while(t--)
{
gets(ch);
int le;
le=strlen(ch);
int re1=work(ch,0,le-1);
gets(ch1);
le=strlen(ch1);
int re2=work(ch1,0,le-1);
if(re1==re2)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}