POJ1686

Written by    19:04 September 29, 2015 

POJ1686

Lazy Math Instructor
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 3766 Accepted: 1307

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

Sample Output

Source

题意

就是比较中缀表达式是否相等,题目中的字母直接用ASCII码来替换,然后看题目的数据的话,比较的只是表达式的最终数值大小,而不是比较表达式是否完全相等,比如a+1和90+8在测试数据中是算两个相等的表达式。

思路

首先把中缀表达式转换成后缀表达式,转换的时候维护一个操作符栈,然后如果优先级大于栈顶就压栈,小于或等于就一直出栈直到当前输入符优先级大于栈顶元素,'(‘优先级最低,直接入栈,碰到’)’才出栈,但是不输出到结果串,然后再计算后缀表达式的值,主要就是用到了栈。

代码

 

 

Category : acmstudy

Tags :