Cod sursa(job #2149647)

Utilizator AndreiBadescuBadescu Andrei-Octavian AndreiBadescu Data 2 martie 2018 20:18:54
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
#include <stack>
#include <queue>

using namespace std;

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

int x,t,dc;
char c,p[128];
bool ok;

queue <int> tl;
stack <int> sv;

inline int Decode ( char c )
{
	switch (c)
	{
		case '+' : return -1;
		case '-' : return -2;
		case '*' : return -3;
		case '/' : return -4;
		case '(' : return -5;
	}
}

inline void doMath ( int &a, int b, int c )
{
	switch (c)
	{
		case -1 : a += b;
			break;

		case -2 : a -= b;
			break;

		case -3 : a *= b;
			break;

		case -4 : a /= b;
			break;
	}
}

inline char Crack ( int x )
{
	switch (x)
	{
		case -1 : return '+';
		case -2 : return '-';
		case -3 : return '*';
		case -4 : return '/';
		case -5 : return '(';
	}
}

inline void Solve ()
{
	if ( ok )
		tl.push (x), x = 0;

	ok = 0;

	switch (c)
	{
		case ')' :
		{
			while ( sv.top() != -5 ) /// '(' = -5
				tl.push ( sv.top() ), sv.pop();

			sv.pop();
			break;
		}

		case '(' :
		{
			sv.push ( -5 );
			break;
		}

		default :
		{
			dc = Decode (c);
			t = dc + 5;

			while ( !sv.empty() && p[sv.top() + 5] >= p[t] )
				tl.push ( sv.top() ), sv.pop();

			sv.push ( dc );
		}
	}
}

int main()
{
	p[1] = p[2] = 2;
	p[3] = p[4] = 1;

	while ( fin >> c )
	{
		if ( c >= '0' && c <= '9' )
			x = x * 10 + c - '0', ok = 1;
		else
			Solve();
	}

	if ( ok )
        tl.push (x);

	while ( !sv.empty() )
		tl.push ( sv.top() ), sv.pop();

	while ( !tl.empty() )
	{
		x = tl.front();

		if ( x >= 0 )
			sv.push (x);
		else
		{
			t = sv.top();
			sv.pop();
			doMath ( sv.top(), t, x );
		}

		tl.pop();
	}

	fout << sv.top();
}