Cod sursa(job #2033001)

Utilizator robuvedVictor Robu robuved Data 5 octombrie 2017 22:53:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;

ifstream in("evaluare.in");
ofstream out("evaluare.out");

const int MAX = 1e5 + 1;
char s[MAX];


bool isOperator(char c)
{
	return c == '+' || c == '-' || c == '*' || c == '/';
}
int Priority(char c)
{
	switch(c)
	{
		case '-':
		case '+': return 0;
		case '/':
		case '*': return 1;
		case '(': return -1;
	}
}
struct Element
{
	int value;
	bool isOperator;
};
Element fp[MAX];
int main()
{
	in >> s;
	int len = strlen(s);
	stack<char> operatori;
	int k = 0;
	for (int i = 0; i < len; i++)
	{
		char c = s[i];
		if (c == '(')
		{
			operatori.push(s[i]);
		}
		else if (isOperator(c))
		{
			while (!operatori.empty() && Priority(c) <= Priority(operatori.top()))
			{
				Element el;
				el.value = operatori.top();
				el.isOperator = true;
				operatori.pop();
				fp[k++] = el;
			}
			operatori.push(c);
		}
		else if (c == ')')
		{
			while (operatori.top() != '(')
			{
				Element el;
				el.value = operatori.top();
				el.isOperator = true;
				operatori.pop();
				fp[k++] = el;
			}
			operatori.pop();
		}
		else
		{
			int number = c - '0';
			i++;
			while (i < len && s[i] >= '0' && s[i] <= '9')
			{
				number = number * 10 + (s[i] - '0');
				i++;
			}
			i--;
			Element el;
			el.value = number;
			el.isOperator = false;
			fp[k++] = el;
		}
	}
	while (!operatori.empty())
	{
		Element el;
		el.value = operatori.top();
		el.isOperator = true;
		operatori.pop();
		fp[k++] = el;
	}
	stack<int> operanzi;
	for (int i = 0; i < k; i++)
	{
		if (fp[i].isOperator)
		{
			int op1 = operanzi.top();
			operanzi.pop();
			int op2 = operanzi.top();
			operanzi.pop();
			double rez = 0;
			switch (fp[i].value)
			{
			case '-': rez = op2 - op1;
				break;
			case '+': rez = op1 + op2;
				break;
			case '*': rez = op1 * op2;
				break;
			case '/': rez = (double)op2 / op1;
				break;
			}
			operanzi.push(rez);
		}
		else
		{
			operanzi.push(fp[i].value);
		}
	}
	out << operanzi.top();
}