题目链接:http://poj.org/problem?id=1686
思路分析:该问题为表达式求值问题,对于字母使用浮点数替换即可,因为输入中的数字只能是单个digit。
代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std; const int MAX_N = ;
const double factor = 1.1;
double number[MAX_N];
char str[MAX_N];
int len, pos; double Expression( );
double Term( );
double Factor( ); void InputExpression( )
{
int i = ;
pos = ;
string str_in;
getline(cin, str_in); for (i = , len = ; i < str_in.length( ); ++i, ++len)
str[len] = str_in[i];
str[len] = '\0';
} char GetCurrentToken( )
{
while (str[pos] == ' ' || str[pos] == '\t')
pos++;
return str[pos];
} char GetNextToken( )
{
++pos;
while (str[pos] == ' ' || str[pos] == '\t')
pos++;
if (pos == len)
return '\n';
else
return str[pos];
} double Expression( )
{
char ch;
double term1 = Term( ); while ((ch = GetCurrentToken( )) == '+' || (ch == '-')) {
GetNextToken( );
double term2 = Term( ); if (ch == '+')
term1 += term2;
else
term1 -= term2;
} return term1;
} double Term( )
{
char ch;
double factor_1 = Factor( ); while ((ch = GetCurrentToken( )) == '*') {
GetNextToken( );
double factor_2 = Factor( ); factor_1 *= factor_2;
}
return factor_1;
} double Factor( )
{
double value = 0.0;
char ch = GetCurrentToken( ); if (ch == '(') {
GetNextToken( );
value = Expression( );
GetNextToken( );
} else if (isdigit(ch)) {
value = ch - '';
GetNextToken( );
}
else if (ch == '\n')
value = -;
else {
if (number[ch - 'A'] == )
value = number[ch - 'A'] = (ch - 'A') * 1.1;
else
value = number[ch - 'A'];
GetNextToken( );
}
return value;
} int main( )
{
int case_time; scanf("%d\n", &case_time);
while (case_time--) {
InputExpression( );
double ans_1 = Expression( ); InputExpression( );
double ans_2 = Expression( ); if (abs(ans_1 - ans_2) < 1e-)
printf("YES\n");
else
printf("NO\n");
} return ;
}