Pagini recente » Cod sursa (job #2686677) | Cod sursa (job #2823876) | Cod sursa (job #1521140) | Cod sursa (job #1630489) | Cod sursa (job #1729809)
#include <fstream>
#include <stack>
#include <algorithm>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
struct operator_{
char op;
unsigned long long priority;
};
int getNormalPriority(char c){
return ((c=='+')||(c=='-'))?2:5;
}
long long fa_operatie(long long op1, long long op2,char op){
if(op == '-') return op2 - op1;
else if(op == '+') return op1 + op2;
else if(op == '/') return op2 / op1;
else return op2 * op1;
}
int main()
{
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string expresie;
f >> expresie;
int i=0;
stack<long long> operanzi;
stack<operator_> operatori;
operator_ op;
if(expresie[0]=='-'){
op.op='-';
op.priority=2;
operatori.push(op);
operanzi.push(0);
i++;
}
unsigned long long priority=1;
while(i<(int)expresie.size()){
if(expresie[i] == '(') {priority*=10; i++;}
else if(expresie[i] == ')') {priority/=10; i++;}
else if(expresie[i]>='0' && expresie[i]<='9'){
string nr="";
nr+=expresie[i++];
while(i<(int)expresie.size() && expresie[i]>='0' && expresie[i]<='9')
nr+=expresie[i++];
unsigned long n = std::stoi(nr);
operanzi.push(n);
}
else{
unsigned long long act_prio = priority;
act_prio*=getNormalPriority(expresie[i]);
op.op = expresie[i];
op.priority = act_prio;
if(operatori.empty() || act_prio > operatori.top().priority)
operatori.push(op);
else{
while(!operatori.empty() && operatori.top().priority >= act_prio){
long op1 = operanzi.top();
operanzi.pop();
long op2 = operanzi.top();
operanzi.pop();
operator_ oop = operatori.top();
operatori.pop();
long op3 = fa_operatie(op1,op2,oop.op);
operanzi.push(op3);
}
operatori.push(op);
}
i++;
}
}
while(!operatori.empty()){
long op1 = operanzi.top();
operanzi.pop();
long op2 = operanzi.top();
operanzi.pop();
operator_ oop = operatori.top();
operatori.pop();
long op3 = fa_operatie(op1,op2,oop.op);
operanzi.push(op3);
}
g << operanzi.top();
return 0;
}