总时间限制:
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;
}