Cod sursa(job #2278603)

Utilizator mihai50000Mihai-Cristian Popescu mihai50000 Data 8 noiembrie 2018 12:18:43
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#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());
}