Cod sursa(job #984414)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 14 august 2013 14:23:52
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <cstring>
#include <sstream>
#include <stack>

void parse(char &c, std::stack<long long>& myS)
{
	long long a, b;
	if(c == '+')
    {
        b = myS.top();
        myS.pop();
        a = myS.top();
        myS.pop();
        myS.push(a + b);
    }
    else if(c == '-')
    {
        b = myS.top();
        myS.pop();
        a = myS.top();
        myS.pop();
        myS.push(a - b);
    }
    else if(c == '*')
    {
        b = myS.top();
        myS.pop();
        a = myS.top();
        myS.pop();
        myS.push(a * b);
    }
    else if(c == '/')
    {
        b = myS.top();
        myS.pop();
        a = myS.top();
        myS.pop();
        myS.push(a / b);
    }
}

long long reg(char *str)
{
	std::stack<char> myS;
	std::stack<long long> myI;
	char c;
	int a, b = strlen(str);
	for(unsigned i = 0; i < b;)
	{
		if(str[i] == '(') myS.push('(');
		else if(str[i] == ')')
		{
			while(myS.top() != '(')
			{
				c = myS.top();
				parse(c, myI);
				myS.pop();
			}
			myS.pop();
		}
		else if(str[i] == '+' || str[i] == '-')
		{
			while(!myS.empty() && myS.top() != '(')
			{
				c = myS.top();
				parse(c, myI);
				myS.pop();
			}
			myS.push(str[i]);
		}
		else if(str[i] == '*' || str[i] == '/')
		{
			while(!myS.empty() && myS.top() != '(' && myS.top() != '+' && myS.top() != '-')
			{
				c = myS.top();
				parse(c, myI);
				myS.pop();
			}
			myS.push(str[i]);
		}
		else
		{
			std::stringstream nstr;
			while(str[i] >= '0' && str[i] <= '9' && i < b)
			{
				nstr << str[i];
				i++;
			}
			nstr >> a;
			myI.push(a);
			continue;
		}
		i++;
	}
	while(!myS.empty())
	{
		c = myS.top();
		parse(c, myI);
		myS.pop();
	}
	return myI.top();
}

int main()
{
	freopen("evaluare.in", "r", stdin);
	freopen("evaluare.out", "w", stdout);
	char *str = new char[100000];
	gets(str);
	printf("%d", reg(str));
	return 0;
}