题目地址
http://poj.org/problem?id=1686
Code
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <stack>
#include <string>
#include <map>
#include <sstream>
#include <vector>
#include <math.h>
#include <algorithm>
#define INF 0x3fffffff
#define N 1005
#define p(x) cout << (x) << endl;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
using namespace std;
typedef long long LL;
int a[N];
int init[N];
int C(char a, char b){
int r ;
switch(b){
case '+':
case '-':
if(a=='(' || a=='#')
r = -1 ; //入栈
else
r = 1 ; //计算
break ;
case '*':
case '/':
if(a=='*' || a=='/' || a==')')
r =1 ; //计算
else
r = -1 ; //入栈
break ;
case '(':
if(a == ')'){
printf("error!\n");
exit(1) ;
}
else{
r = -1 ; //入栈
}
break ;
case ')':
if(a == '(')
r = 0 ;
else
r = 1 ;
break ;
case '#':
if(a=='#')
r = 0 ;
else
r = 1 ;
break ;
}
return r ;
}
int cal(int a, int b , char c){
int res ;
switch(c){
case '+': res = a + b ; break ;
case '-': res = a - b ; break ;
case '*': res = a * b ; break ;
case '/': res = a / b ; break ;
}
//printf("%d = %d %c %d\n", res, a, c, b);
return res ;
}
int hand(string s) {
map<char, int> mp;
for (int i = 0; i <= 9; i++) {
mp['0'+i] = i;
}
int v = 1;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ' || s[i] == '\t') {
continue;
}
if (s[i] == '(' || s[i] == ')' || s[i] == '+' || s[i] == '-' || s[i] == '*') {
continue;
}
if ('0' <= s[i] && s[i] <= '9') {
continue;
}
// not same with 0~9
if (mp[s[i]] == 0) {
mp[s[i]] = s[i] - 'A' + 10;
}
}
//p(mp['a'])
//p(mp['b'])
//p(mp['c'])
//p(s)
stack<char> f; f.push('#');
stack<int> d;
int x, y;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ' || s[i] == '\t') {
continue;
}
char pre = f.top();
char c = s[i];
switch (c) {
case '(' :
case ')' :
case '+' :
case '-' :
case '*' :
case '#' :
switch(C(pre, c)){
case 0:
f.pop();
break ;
case -1 :
f.push(c);
break ;
case 1 :
i--;
f.pop();
int a = d.top(); d.pop();
int b = d.top(); d.pop();
d.push(cal(b, a, pre));
break ;
}
break;
default : d.push(mp[c]); break;
}
}
return d.top();
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#else
//
#endif
int n;
cin >> n;
getchar();
for (int i = 0; i < n; i++) {
string s1, s2;
getline(cin, s1);
getline(cin, s2);
s1 += "#";
s2 += "#";
int ans1 = hand(s1);
int ans2 = hand(s2);
//cout << ans1 << " " << ans2 << endl;
if (ans1 == ans2) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}