Cod sursa(job #2281244)

Utilizator mihai50000Mihai-Cristian Popescu mihai50000 Data 11 noiembrie 2018 19:28:33
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 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");

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;
	cin >> 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)); 
	} 
	
	cout << numbers.top();
	
}