Cod sursa(job #963802)

Utilizator alexandru70Ungurianu Alexandru alexandru70 Data 19 iunie 2013 15:46:58
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.67 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
#include <sstream>

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

std::string inExp;

bool isOp(char c)
{
	switch (c)
	{
		case '+': case '-': case '*': case '/':
			return true;
		default:
			return false;
	}
}

int getPrir(char op)
{
	switch (op)
	{
		case '+': case '-':
			return 1;
		case '*': case '/':
			return 2;
		case ')': case '(':
			return 0;
	}
}

int main()
{
	std::getline(in,inExp);
	std::stack<char> opStack;
	std::stringstream polNotExp;
	for(auto it = inExp.begin(); it!=inExp.end(); it++)
	{
		if(isOp(*it))
		{
			if(it == inExp.begin()||isOp(*(it-1))||*(it-1)=='(')
			{
				polNotExp << *it;
				continue;
			}
			while( !opStack.empty() && getPrir(*it)<getPrir(opStack.top()))
			{
				polNotExp << opStack.top() << ' ';
				opStack.pop();
				//std::cerr << "Pushing Operator\n";
			}
			opStack.push(*it);
		}
		else if(*it=='(')
			opStack.push(*it);
		else if(*it==')')
		{
			while(opStack.top()!='(')
			{
				polNotExp << opStack.top() << ' ';
				opStack.pop();
				//std::cerr << "Pushing Operator(Para)\n";
			}
			opStack.pop();
		}
		else
		{
			do
			{
				polNotExp << *it;
				it++;
				//std::cerr << "Pushing Operand\n";
			}while(it!=inExp.end() && !isOp(*it) && *it!='(' && *it!=')');
			polNotExp << ' ';
			it--;
		}
	}
	while(!opStack.empty())
	{
		polNotExp << opStack.top() << ' ';
		opStack.pop();
	}
	std::cerr << polNotExp.str() << '\n';
	std::stack<int> solve;
	bool nextIsSigned = false;
	while(!polNotExp.eof())
	{
		if(polNotExp.peek()==-1)break;
		if(polNotExp.peek()<='9'&&polNotExp.peek()>='0')
		{
			int t;
			polNotExp >> t;
			if(nextIsSigned)t=-t;
			//std::cerr << t << ' ';
			solve.push(t);
		}
		else if(isOp(polNotExp.peek()))
		{
			char c;
			polNotExp >> c;
			if(polNotExp.peek()<='9'&&polNotExp.peek()>='0')
			{
				if(c=='-')
					nextIsSigned=true;
				continue;
			}
			//std::cerr << c << ' ';
			int opr1,opr2;
			opr2=solve.top();
			solve.pop();
			//std::cerr << "Ok Op1 ";
			opr1=solve.top();
			//std::cerr << "Ok Op2 ";
			solve.pop();
			switch(c)
			{
				case '+':
					solve.push(opr1+opr2);
					//std::cerr << opr1 << ' ' << opr2 <<" + " << opr1+opr2 << '\n';
					break;
				case '-':
					solve.push(opr1-opr2);
					//std::cerr << opr1 << ' ' << opr2 <<" - " << opr1-opr2 << '\n';
					break;
				case '*':
					solve.push(opr1*opr2);
					//std::cerr << opr1 << ' ' << opr2 <<" * " << opr1*opr2 << '\n';
					break;
				case '/':
					solve.push(opr1/opr2);
					//std::cerr << opr1 << ' ' << opr2 <<" / " << opr1/opr2 << '\n';
					break;
			}
		}
		polNotExp.ignore();
	}
	//std::cerr << solve.size() << '\n';
	out << solve.top();
}