Pagini recente » Cod sursa (job #2075607) | Cod sursa (job #2351434) | Cod sursa (job #2262516) | Cod sursa (job #1958934) | Cod sursa (job #2278603)
#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");
#define pb push_back
#define F first
#define S second
typedef pair <int, int> pii;
stack <char> s;
unordered_map <char, int> priority;
stack <pii> numbers;
stack <pii> operators;
vector <pii> rpn;
void init()
{
priority['+'] = 1;
priority['-'] = 1;
priority['*'] = 2;
priority['/'] = 2;
}
main()
{
init();
bool last = 1;
string forParse;
f >> forParse;
bool c_number = 0;
int nr = 0;
for(auto i : forParse)
if(i >= '0' && i <= '9')
{
c_number = 1;
nr = nr * 10 + i - '0';
}
else
{
if(c_number == 1)
{
c_number = 0;
rpn.pb({nr, 0});
nr = 0;
}
if(i == ')')
{
while(s.top() != '(')
{
rpn.pb({s.top(), 1});
s.pop();
}
s.pop();
continue;
}
if(i == '(')
{
s.push(i);
continue;
}
if(!s.empty() && s.top() == '(')
{
s.push(i);
continue;
}
while(!s.empty() && s.top() != '(' && priority[s.top()] >= priority[i])
{
rpn.pb({s.top(), 1});
s.pop();
}
s.push(i);
}
if(c_number)
rpn.pb({nr, 0});
while(!s.empty())
{
rpn.pb({s.top(), 1});
s.pop();
}
for(auto i : rpn)
if(i.S == 0)
s.push(i.F);
else
{
int p2 = s.top();
s.pop();
int p1 = s.top();
s.pop();
switch(char(i.F))
{
case('+'): s.push(p1 + p2); break;
case('-'): s.push(p1 - p2); break;
case('/'): s.push(p1 / p2); break;
case('*'): s.push(p1 * p2); break;
}
}
g << int(s.top());
}