Pagini recente » Istoria paginii utilizator/gosu_gamer | Cod sursa (job #1823938) | Cod sursa (job #725059) | Cod sursa (job #2068233) | Cod sursa (job #2281245)
//#include <bits/stdc++.h>
#include <fstream>
#include <vector>
#include <bitset>
#include <unordered_map>
#include <algorithm>
#include <queue>
#include <math.h>
#include <iomanip>
#include <stack>
#include <string.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
stack <int> numbers;
stack <char> operators;
int priority(char op)
{
if(op == '+' || op == '-')
return 1;
if(op == '*' || op == '/')
return 2;
return 0;
}
int calc(char op, int x, int y)
{
switch(op)
{
case '+': return x + y;
case '-': return x - y;
case '/': return x / y;
case '*': return x * y;
}
}
main()
{
string s;
f >> s;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '(')
operators.push(s[i]);
else
if(s[i] >= '0' && s[i] <= '9')
{
int nr = 0;
while(i < s.size() && s[i] >= '0' && s[i] <= '9')
{
nr = (nr * 10) + (s[i] - '0');
i++;
}
if(i < s.size())
i--;
numbers.push(nr);
}
else
if(s[i] == ')')
{
while(operators.top() != '(')
{
int p1 = numbers.top();
numbers.pop();
int p2 = numbers.top();
numbers.pop();
char op = operators.top();
operators.pop();
numbers.push(calc(op, p2, p1));
}
operators.pop();
}
else
{
while(!operators.empty() && priority(operators.top()) >= priority(s[i]))
{
int p1 = numbers.top();
numbers.pop();
int p2 = numbers.top();
numbers.pop();
char op = operators.top();
operators.pop();
numbers.push(calc(op, p2, p1));
}
operators.push(s[i]);
}
}
while(!operators.empty())
{
int p1 = numbers.top();
numbers.pop();
int p2 = numbers.top();
numbers.pop();
char op = operators.top();
operators.pop();
numbers.push(calc(op, p2, p1));
}
g << numbers.top();
}