Pagini recente » Cod sursa (job #2088769) | Cod sursa (job #2389386) | Cod sursa (job #302037) | Cod sursa (job #2405746) | Cod sursa (job #1906931)
#include <iostream>
#include <fstream>
#include <stack>
#include <unordered_map>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string e;
stack<int> n;
stack<char> op;
unordered_map<char, int> pr;
void init(){
pr['(']=0, pr[')']=0;
pr['+']=1, pr['-']=1;
pr['*']=2, pr['/']=2;
}
int calc(int a, int b, char x){
if(x=='+')return a+b;
else if(x=='-')return a-b;
else if(x=='*')return a*b;
else return a/b;
}
int main(){
getline(in, e);
int nr, a, b;
init();
for(int i=0; i<e.size(); i++){
if('0'<=e[i]&&e[i]<='9'){
nr=0;
while(i<e.size()&&'0'<=e[i]&&e[i]<='9'){
nr=nr*10+(e[i]-'0');
i++;
}
i--;
n.push(nr);
}else if(e[i]=='('){
op.push('(');
if(e[i+1]=='-')n.push(-1),op.push('*'),i++;
}else if(e[i]==')'){
while(pr[op.top()]>0){
b=n.top(), n.pop();
a=n.top(), n.pop();
nr=calc(a, b, op.top());
n.push(nr);
op.pop();
}
op.pop();
}else{
while(!op.empty()&&pr[op.top()]>=pr[e[i]]){
b=n.top(), n.pop();
a=n.top(), n.pop();
nr=calc(a, b, op.top());
n.push(nr);
op.pop();
}
op.push(e[i]);
}
}
while(!op.empty()){
b=n.top(), n.pop();
a=n.top(), n.pop();
nr=calc(a, b, op.top());
n.push(nr);
op.pop();
}
out<<n.top();
return 0;
}