c++表达式计算

总时间限制: 

20000ms

单个测试点时间限制: 

1000ms

内存限制: 

262144kB

描述

给定一个四则运算表达式,请你计算它的结果。
例如 (1+2)*(3+4) 结果是 21。
表达式中的运算符包含 "+"、"-"、"*"、"/"、"("、")" ,其中 "/" 是整除,即 7/2=3,(-7)/2=-3 。(和 C++中的整除运算规则相同)
表达式中的数均为正整数,保证中间及最终计算结果在 -2147483648 ~ 2147483647 之间。

输入

一个字符串S,代表表达式。

输出

一个整数表示答案。

样例输入

样例输入1
(1-2)*(3+4-(1+3-2)*3)

样例输入2
1-2-3-4+5-6+7+8+9

样例输入3
18*(3-2*31*7/5+9-10)-1*2/(128+9)-102030-1+3

样例输出

样例输出1
-1

样例输出2
15

样例输出3
-103540

思路:建表达式树

code:

#include<bits/stdc++.h> 
#define endl '\n'
using namespace std;
struct T{
	int tp,num,l,r;
	char op;
}t[3010];
string s;
int tot,len;
stack<int> nst;
stack<char> cst;
int pri(char op){
	if(op=='+'||op=='-') return 1;
	if(op=='*'||op=='/') return 2;
	return 3;
}
int dfs(int u){
	if(t[u].tp==0) return t[u].num;
	if(t[u].op=='+') return dfs(t[u].l)+dfs(t[u].r);
	if(t[u].op=='-') return dfs(t[u].l)-dfs(t[u].r);
	if(t[u].op=='*') return dfs(t[u].l)*dfs(t[u].r);
	if(t[u].op=='/') return dfs(t[u].l)/dfs(t[u].r);
	return 0;
} 
void cac(){
	int x,y;char op=cst.top();cst.pop();
	y=nst.top();nst.pop();
	x=nst.top();nst.pop();
	t[++tot]={1,0,x,y,op};
	nst.push(tot);
}
int main(){
	cin>>s;
	len=s.size();
	for(int i=0;i<len;i++){
		if(isdigit(s[i])){
			int val=0;
			for(;i<len&&isdigit(s[i]);i++) val=val*10+s[i]-'0';
			t[++tot]={0,val,0,0,0};
			nst.push(tot);
			i--;
		}
		else{
			if(s[i]=='(') cst.push(s[i]);
			else if(s[i]==')'){
				while(cst.size()&&cst.top()!='(') cac();
				cst.pop();
			}
			else{
				while(cst.size()&&cst.top()!='('&&pri(s[i])<=pri(cst.top())) cac();
				cst.push(s[i]); 
			}
		}
	}
	while(!cst.empty()) cac();
	cout<<dfs(tot)<<endl;
	return 0;
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值