标签:return == 优先 lse 计算 lang stream cout 表达式
算符优先文法的应用
#include<iostream>
using namespace std;
const int N = 110;
char sb[N], pp = -1;
int dg[N], qq = -1;
int cmp(char a, char b){
if(a == ‘(‘) return 0;
if(b == ‘)‘) return 1;
if(b == ‘(‘) return 0;
if(a == b) return 1;
if(a == ‘*‘ || a == ‘/‘) return 1;
if(b == ‘*‘ || b == ‘/‘) return 0;
return 1;
}
int calc(int a, int b, char op){
switch(op){
case ‘+‘: return a + b;
case ‘-‘: return b - a;
case ‘*‘: return a * b;
case ‘/‘: return b / a;
}
}
int solve(string &s){
int i = 0, len = s.size();
while(i < len){
int p = 0;
while(i < len && s[i] >= ‘0‘ && s[i] <= ‘9‘)
p = p * 10 + s[i ++] - ‘0‘;
if(p) dg[++ qq] = p;
if(i < len)
if(pp == -1) sb[++ pp] = s[i];
else{
while(~pp && cmp(sb[pp], s[i]) && sb[pp] != ‘(‘){
int a = dg[qq --], b = dg[qq --];
dg[++ qq] = calc(a, b, sb[pp]);
pp --;
}
if(s[i] == ‘)‘) pp --;
else sb[++ pp] = s[i];
}
i ++;
}
while(~pp){
int a = dg[qq --], b = dg[qq --];
dg[++ qq] = calc(a, b, sb[pp]);
pp --;
}
return dg[0];
}
int main(){
string s;
cin >> s;
cout << solve(s);
return 0;
}
标签:return == 优先 lse 计算 lang stream cout 表达式
原文地址:https://www.cnblogs.com/tomori/p/13678218.html