Pagini recente » Cod sursa (job #1863068) | Cod sursa (job #2006628)
#include<iostream>
#include<vector>
#include<stack>
#include<cstring>
#include<cstdio>
using namespace std;
int priority(char a){
// 3 high priority - 2 medium priority - 1 low priority
if(a=='(' || a==')')
return 3;
if(a=='*' || a=='/')
return 2;
else return 1;
}
bool isOperator(char a){
if(strchr("()*/+-",a))
return 1;
}
char infix[100001];
char postfix[100001];
stack<char> order;
int main(){
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
cin.getline(infix,100001);
int N = strlen(infix);
int j = 0;
for(int i = 0; i < N;){
while(infix[i] == ' ')
++i;
if(!isOperator(infix[i])){
while(!isOperator(infix[i]))
postfix[j++] = infix[i++];
postfix[j++] = ' ';
}else if(infix[i] == '('){
order.push('(');
++i;
}else if(infix[i] == ')'){
while(order.top() != '('){
postfix[j++] = order.top();
postfix[j++] = ' ';
order.pop();
}
order.pop();
++i;
}else if(isOperator(infix[i])){
if(order.empty()){
order.push(infix[i]);
}else{
while(!order.empty() && order.top() != '(' && priority(order.top()) >= priority(infix[i])){
postfix[j++] = order.top();
postfix[j++] = ' ';
order.pop();
}
order.push(infix[i]);
}
++i;
}
}
while(!order.empty()){
postfix[j++] = order.top();
postfix[j++] = ' ';
order.pop();
}
//cout<<postfix;
int M = strlen(postfix);
int a,b;
stack<int> st;
for(int i = 0; i < M; i+=2){
if(isOperator(postfix[i])){
a = st.top();
st.pop();
b = st.top();
st.pop();
switch(postfix[i]){
case '+': st.push(a+b);break;
case '-': st.push(b-a);break;
case '*': st.push(b*a);break;
case '/': st.push(b/a);break;
}
}else{
a=postfix[i]-'0';
while(postfix[i+1]!=' ')
a = a*10 + postfix[++i]-'0';
st.push(a);
}
}
cout<<st.top();
return 0;
}