Cod sursa(job #672359)

Utilizator BitOneSAlexandru BitOne Data 1 februarie 2012 22:10:24
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;


inline int priority( char op )
{
	switch( op )
	{
		case '(' : return -5;
		case '+' : ;
		case '-' : return 1;
		case '*' : ;
		case '/' : return 2;
		default  : return 5;
	}
}
string transform( string expresion )
{
	int p;
	string t;
	stack<char> s;
	string::const_iterator it=expresion.begin(), iend=expresion.end();
	
	while( it < iend )
	{
		if( *it >= '0' && *it <= '9' )
		{
			for( ; it < iend && *it >= '0' && *it <= '9'; ++it )
				t.push_back( *it );
			t.push_back( ',' );
		}
		else if( '(' == *it )
		     {
				 ++it;
				 s.push( '(' );
			 }
			 else if( ')' == *it )
			      {
					  ++it;
					  for( ; '(' != s.top(); t.push_back(s.top()), s.pop() );
					  s.pop();
				  }
				  else {
							p=priority(*it);
							for( ; !s.empty() && p <= priority(s.top()); t.push_back(s.top()), s.pop() );
							s.push( *it );
							++it;
					   }
	}
	for( ; !s.empty(); t.push_back(s.top()), s.pop() );
	return t;	
}
int eval( string expresion )
{
	int x, a, b;
	stack< int > s;
	string::const_iterator it, iend;
	
	expresion=transform( expresion );
	
	for( it=expresion.begin(), iend=expresion.end(); it < iend; ++it )
	{
		if( *it >= '0' && *it <= '9' )
		{
			for( x=0 ; it < iend && *it >= '0' && *it <= '9'; ++it )
				x=x*10+*it-'0';
			s.push(x);
		}
		else {
				x=priority(*it);
				if( x >= 1 && x <= 2 )
				{
					b=s.top(); s.pop();
					a=s.top(); s.pop();
					switch( *it )
					{
						case '+' : s.push(a+b); break;
						case '-' : s.push(a-b); break;
						case '/' : s.push(a/b); break;
						case '*' : s.push(a*b);
					}
				}
			 }
	}
	return s.top();		
}

int main() 
{
	string exp;
	
	ifstream in( "evaluare.in" );
	getline( in, exp );
	
	ofstream out( "evaluare.out" );
	out<<eval(exp)<<'\n';
	
	return EXIT_SUCCESS;
}