Cod sursa(job #984412)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 14 august 2013 14:18:36
Problema Evaluarea unei expresii Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <fstream>
#include <string>
#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(std::string& str)
{
	std::stack<char> myS;
	std::stack<long long> myI;
	char c;
	int a;
	for(unsigned i = 0; i < str.length();)
	{
		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')
			{
				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()
{
	std::ifstream in("evaluare.in");
	std::ofstream out("evaluare.out");
	std::string str;
	getline(in, str);
	out << reg(str);
	return 0;
}