Pagini recente » Cod sursa (job #1280592) | Cod sursa (job #1850448) | Cod sursa (job #1934604) | Cod sursa (job #9193) | Cod sursa (job #2705060)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string s;
int priority(char op) {
return 1 + (op != '+' && op != '-');
}
int evaluate(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return -1;
}
}
string read(string &s, int &p) {
string nr;
while (p < s.size() && isdigit(s[p])) {
nr += s[p++];
}
return nr;
}
int convert(string s) {
int nr = 0;
for (auto it : s) {
nr = 10 * nr + it - '0';
}
return nr;
}
vector<string> infix_to_postfix(string s) {
vector<string> postfix;
vector<string> operators;
int p = 0;
for (; p < s.size(); ) {
if (isdigit(s[p])) {
postfix.push_back(read(s, p));
} else if (s[p] == '(') {
operators.push_back(string(1, s[p++]));
} else if (s[p] == ')') {
while (operators.size() > 0 && operators.back() != "(") {
postfix.push_back(operators.back());
operators.pop_back();
}
operators.pop_back();
p++;
} else {
while (operators.size() > 0 && operators.back() != "(" && priority(operators.back()[0]) >= priority(s[p])) {
postfix.push_back(operators.back());
operators.pop_back();
}
operators.push_back(string(1, s[p++]));
}
}
while (operators.size() > 0) {
postfix.push_back(operators.back());
operators.pop_back();
}
return postfix;
}
int evaluate_postfix(vector<string> v) {
vector<int> operands;
int ans = 0, a, b;
for (auto it : v) {
if (isdigit(it[0])) {
operands.push_back(convert(it));
} else {
b = operands.back();
operands.pop_back();
a = operands.back();
operands.pop_back();
operands.push_back(evaluate(a, b, it[0]));
}
}
return operands[0];
}
int main() {
in >> s;
out << evaluate_postfix(infix_to_postfix(s));
return 0;
}