9-表达式求值

http://nyoj.top/problem/1272 

#include <iostream>
#include <stack>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=1005;
int cmp[6][6]={//横为当前,竖为栈顶。1表示栈顶优先级大于当前,此时弹出计算。-1表示小于当前,此时入栈。0表示相等,100为不存在。 
1,-1,-1,1,1,1,
1,1,-1,1,1,1,
-1,-1,-1,0,-1,100,
100,100,100,100,100,100,
-1,-1,-1,1,-1,1,
-1,-1,-1,-1,100,0
};
char s[maxn];
char tmp[maxn];
int T;
bool isnum(char x){
	if(x<='9'&&x>='0')
	return true;
	return false;
}
int cal(int a,int b,char c){
	if(c=='+'){
		return a+b;
	}
	if(c=='*'){
		return a*b;
	}
	if(c==','){
		int sum1=0;
		int sum2=0;
		while(a){
			sum1+=a%10;
			a/=10;
		}
		while(b){
			sum2+=b%10;
			b/=10;
		}
		return sum1>sum2?sum1:sum2;
	}
}
int ctoi(char x){
	switch(x){
		case '+':
			return 0;
		case '*':
			return 1;
		case '(':
			return 2;
		case ')':
			return 3;
		case ',':
			return 4;
		case '#':
			return 5;
	}
}
int main(){
	scanf("%d",&T);
	while(T--){
		scanf("%s",tmp);
		int len=0;
		for(int i=0;i<strlen(tmp);i++){
			if(tmp[i]=='S'||tmp[i]=='m'||tmp[i]=='a'||tmp[i]=='x')
			continue;
			s[len++]=tmp[i];
		}
		s[len++]='#';
		/*for(int i=0;i<len;i++){
			printf("%c",s[i]);
		}
		printf("\n");*/
		stack<int>opnd;
		stack<char>optr;
		optr.push('#');
		for(int i=0;i<len;i++){
			if(isnum(s[i])){
				opnd.push(atoi(&s[i]));
				while(isnum(s[i+1]))
				i++; 
			}
			else{
				if(cmp[ctoi(optr.top())][ctoi(s[i])]==-1){
					optr.push(s[i]);
				}
				else if(cmp[ctoi(optr.top())][ctoi(s[i])]==1){
					int a=opnd.top(); opnd.pop();
					int b=opnd.top(); opnd.pop();
					char c=optr.top(); optr.pop();
					int d=cal(a,b,c);
					opnd.push(d);
					i--;
				}
				else{
					optr.pop();
				}
			}
		}
		printf("%d\n",opnd.top());
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值