Pagini recente » Cod sursa (job #2960229) | Cod sursa (job #2167987) | Cod sursa (job #1277468) | Cod sursa (job #582214) | Cod sursa (job #2302848)
#include <iostream>
#include <stack>
#include <string>
#include <fstream>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
istream & in = fin;
ostream & out = fout;
stack<int> numbas;
stack<char> operators;
int GetPriority(char c)
{
if(c == '+' || c == '-'){
return 0;
}else if(c == '*' || c == '/'){
return 1;
}else if(c == '('){
return -1;
}
}
bool IsNumba(char c)
{
return (c >= '0' && c <= '9');
}
int ToNumba(char c)
{
return (c - '0');
}
int Eval(char op, int a, int b)
{
if(op == '+'){
return a+b;
}else if(op == '-'){
return a-b;
}else if(op == '*'){
return a*b;
}else if(op == '/'){
return a/b;
}
return 0;
}
int Dijkstra(string s)
{
char c;
for(int i = 0; i < s.size(); i++){
c = s[i];
if(IsNumba(c)){
int a = ToNumba(c);
while(IsNumba(s[i+1])){
a *= 10;
a += ToNumba(s[i+1]);
i++;
}
numbas.push(a);
}else if(c == '('){
operators.push(c);
}else if(c == ')'){
while(operators.top() != '('){
int b = numbas.top();numbas.pop();
int a = numbas.top();numbas.pop();
numbas.push(Eval(operators.top(), a, b));
operators.pop();
}
operators.pop();
}else{
while(!operators.empty() && GetPriority(operators.top()) >= GetPriority(c)){
int b = numbas.top();numbas.pop();
int a = numbas.top();numbas.pop();
numbas.push(Eval(operators.top(), a, b));
operators.pop();
}
operators.push(c);
}
}
while(!operators.empty()){
int b = numbas.top();numbas.pop();
int a = numbas.top();numbas.pop();
numbas.push(Eval(operators.top(), a, b));
operators.pop();
}
return numbas.top();
}
int main()
{
string s;
in >> s;
out << Dijkstra(s);
return 0;
}