ZOJ 1418 Lazy Math Instructor

先把中缀表达式转换成后缀表达式,题目中已经说了所有算符优先级相等,这里就不用考虑优先级.

然后计算后缀表达式,对每个字符的值取字符表的位置就可以了.


#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
#include <string.h>
using namespace std;
int pri[128];
char buf[128];

long long getVal(){
	stack<char> stk;
	int i = 0, len = strlen(buf);
	string postExp = "";
	while(i < len){
		char ch = buf[i];
		if(isalpha(ch)){
			postExp += ch;
		}else if(isdigit(ch)){
			string tmp = "";
			for(; i < len && isdigit(buf[i]);++i)tmp += buf[i];
			postExp += " " + tmp + " ";
			continue;
		}
		else if(ch == '('){
			stk.push(ch);
		}else if(ch == ')'){
			while(stk.size()){
				char t = stk.top();
				stk.pop();
				if(t == '(')break;
				postExp += t;
			}
		}else if(ch == '+' || ch == '-' || ch =='*'){
			while(stk.size() && stk.top() != '('){
				postExp += stk.top();
				stk.pop();
			}
			stk.push(ch);
		}
		++i;
	}
	while(stk.size()){
		postExp += stk.top();
		stk.pop();
	}
	i = 0;
	stack<long long> vs;
	while(i < postExp.size()){
		char ch = postExp[i];
		if(isdigit(ch)){
			long long t = ch - '0';
			for(++i; i < postExp.size() && isdigit(postExp[i]);++i){
				t = t * 10 + (ch -'0');
			}
			vs.push(t);
			continue;
		}else if(isalpha(ch)){
			vs.push(ch - ('a' - 1));
		}else if(ch == '+' || ch == '-' || ch =='*'){
			long long op1, op2;
			op2 = vs.top();
			vs.pop();
			op1 = vs.top();
			vs.pop();
			if(ch == '+')
				vs.push(op1 + op2);
			else if(ch == '-')
				vs.push(op1 - op2);
			else if(ch == '*')
				vs.push(op1 * op2);
		}
		++i;
	}
	return vs.top();
}
int main(){
	int T;
	scanf("%d\n", &T);
	while(T--){
		gets(buf);
		long long ans1 = getVal();
		gets(buf);
		long long ans2 = getVal();
		if(ans1 == ans2){
			printf("YES\n");
		}else{
			printf("NO\n");
		}
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值