#include<bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i <= b ; i ++ )
#define per(i, a, b) for(int i = a; i >= b ; i -- )
const int maxn = 1e4 + 10;
typedef struct myStack
{
int data[maxn];
int top;
}mystack;
typedef struct charStack
{
char op[maxn];
int top;
}charstack;
void init1(mystack * S)
{
S -> top = 0;
}
void init2(charstack * Cs)
{
Cs -> top = 0;
}
void push1(mystack * S, int x){
S -> data[S -> top ++ ] = x;
}
void push2(charstack * Cs, char c){
Cs -> op[Cs -> top ++ ] = c;
}
char compare(char a, char b){
int m,n;
char OP[][7]={
/*运算符之间的优先级制作成一张表格*/
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=','0'},
{'>','>','>','>','0','>','>'},
{'<','<','<','<','<','0','='}
};
switch(a){
case '+': m=0; break;
case '-': m=1; break;
case '*': m=2; break;
case '/': m=3; break;
case '(': m=4; break;
case ')': m=5; break;
case '#': m=6; break;
}
switch(b){
case '+': n=0; break;
case '-': n=1; break;
case '*': n=2; break;
case '/': n=3; break;
case '(': n=4; break;
case ')': n=5; break;
case '#': n=6; break;
}
return OP[m][n];
}
void pop1(mystack * S){
S -> top -- ;
}
void pop2(charstack * Cs)
{
// char xx = op[Cs -> top -- ];
Cs -> top -- ;
// return xx;
}
int con(int a, int b, char operators)
{
int res;
switch(operators){
case'+':{
res = a + b;
break;
}
case'-':{
res = b - a;
break;
}
case'*':{
res = a * b;
break;
}
case'/':{
res = b/a;
break;
}
}
return res;
}
using namespace std;
int main()
{
mystack S;
charstack Cs;
init1(&S);
init2(&Cs);
string s;
cin >> s;
int len = s.length();
int ans = 0;
rep(i, 0, len - 1){
int cnt = 0, k = 0;
if(isdigit(s[i])){
while(isdigit(s[i])){
cnt = cnt * pow(10, k) + (s[i] - '0');
i ++, k ++ ;
}
// cout << cnt << s[i] << "fw" << endl;
push1(&S, cnt);
push2(&Cs, s[i]);
} else {
push2(&Cs, s[i]);
}
if(Cs.top >= 2){
char x = Cs.op[Cs.top - 1];
char y = Cs.op[Cs.top - 2];
// cout << y << " " << x << "x";
// cout << compare(x, y) <<"fhuah"<< endl;
// cout << compare(x, y)<<endl;
switch (compare(x, y)){
case '=': {
pop2(&Cs);
pop2(&Cs);
break;
}
case '>': {
i ++;
int r;
if(!isdigit(s[i])){
r = con(S.data[S.top - 1], S.data[S.top - 2], Cs.op[Cs.top - 2]);
pop1(&S);
pop1(&S);
pop2(&Cs);
pop2(&Cs);
pop2(&Cs);
i -- ;
} else{
cnt = 0, k = 0;
while(isdigit(s[i])){
cnt = cnt * pow(10, k) + (s[i] - '0');
i ++, k ++ ;
}
i--;
r = con(S.data[S.top - 1], cnt, Cs.op[Cs.top - 1]);
pop1(&S);
pop2(&Cs);
}
// cout << r << "fhauhfj\n";
push1(&S, r);
break;
}
}
}
}
cout << S.data[S.top - 1];
}
2021 - 10 - 14多项式求值
最新推荐文章于 2024-10-02 23:40:03 发布