HDU 1686 Lazy Math Instructor(中缀转后缀,栈模拟)

HDU 1686 Lazy Math Instructor(中缀转后缀,栈模拟)

ACM

题目地址:POJ 1686 Lazy Math Instructor

题意: 
问两个等式是否相等。

分析: 
栈模拟把中缀转后缀,然后用后缀算出值,再进行比较。 
直接把字母看成ASCII值就行了。

代码

/*
*  Author:      illuz <iilluzen[at]gmail.com>
*  Blog:        http://blog.csdn.net/hcbbt
*  File:        1686.cpp
*  Create Date: 2014-08-04 20:05:00
*  Descripton:  simulate, expression 
*/

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;

const int N = 90;

int prior(char c) {
    if(c == '(')
        return 0;
    else if (c == '*')
        return 2;
    else
        return 1;
}

void convert(char* s, char* tmp) {
	int len = strlen(s), n = 0;
	int res, rhs, lhs;
	stack<int> st;

	for (int i = 0; i < len; i++) {
		char r = s[i];
		if (r == ' ')
			continue;
		if ((r >= 'a' && r <= 'z') || (r >= '0' && r <= '9'))
			tmp[n++] = r;
		else {
			if (st.empty() || r == '(')
				st.push(r);
			else if (r == ')') {
				while (!st.empty() && st.top() != '(') {
					tmp[n++] = st.top();
					st.pop();
				}
				st.pop();
			} else {
				while (!st.empty() && prior(r) <= prior(st.top())) {
					tmp[n++] = st.top();
					st.pop();
				}
				st.push(r);
			}
		}
	}

	while (!st.empty()) {
		tmp[n++] = st.top();
		st.pop();
	}
	tmp[n] = 0;
}

int calc(char* t) {
	int len = strlen(t);
	int rhs = 0, lhs = 0;
	stack<int> st;

	for (int i = 0; i < len; i++) {
		if (t[i] >= '0' && t[i] <= '9') 
			st.push(t[i] - '0');
		else if (t[i] <= 'z' && t[i] >= 'a')
			st.push(t[i]);
		else {
			rhs = st.top();
			st.pop();
			lhs = st.top();
			st.pop();
			if (t[i] == '+')
				st.push(rhs + lhs);
			else if (t[i] == '-')
				st.push(lhs - rhs);
			else
				st.push(rhs * lhs);
		}
	}
	return st.top();
}

int main() {
	char str[N], temp[N];
	int n;
	scanf("%d\n",&n);
	while (n--) {

		gets(str);
		convert(str, temp);
		int ans1 = calc(temp);

		gets(str);
		convert(str, temp);
		int ans2 = calc(temp);

		if (ans1 == ans2)
			printf("YES\n");
		else
			printf("NO\n");
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值