Pagini recente » Cod sursa (job #1632978) | Cod sursa (job #2656032) | Cod sursa (job #1033822) | Cod sursa (job #886599) | Cod sursa (job #2371156)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <map>
#include <stack>
#define ll long long
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
int getresult(int a, int b, char c) {
if(c == '+')
return a + b;
if(c == '-')
return a - b;
if(c == '*')
return a * b;
if(c == '/')
return a / b;
}
bool isoperator(char c) {
if(c == '+' || c == '-' || c == '*' || c == '/')
return 1;
return 0;
}
int priority(char c) {
if(c == '+' || c == '-')
return 1;
if(c == '/' || c == '*')
return 2;
}
int main() {
string s;
in >> s;
stack<char> op;
stack<int> values;
int i = 0;
while(i < s.size()) {
if(s[i] == '(') {
op.push(s[i]);
i ++;
} else if(s[i] == ')') {
while(op.top() != '(') {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
a = getresult(b, a, op.top());
values.push(a);
op.pop();
}
op.pop();
i ++;
} else if(isoperator(s[i])) {
while(op.size() && isoperator(op.top()) && priority(s[i]) <= priority(op.top())) {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
a = getresult(b, a, op.top());
values.push(a);
op.pop();
}
op.push(s[i]);
i ++;
} else {
int nr = 0;
while(i < s.size() && isdigit(s[i])) {
nr = nr * 10;
nr += (s[i] - '0');
i ++;
}
values.push(nr);
}
}
while(op.size()) {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
a = getresult(b, a, op.top());
values.push(a);
op.pop();
}
out << values.top();
return 0;
}