Cod sursa(job #360870)

Utilizator alexandru92alexandru alexandru92 Data 2 noiembrie 2009 15:47:34
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.26 kb
#include <stack>
#include <cmath>
#include <string>
#include <fstream>
#define InFile "evaluare.in"
#define OutFile "evaluare.out"

/*
 *
 */
using namespace std;
ifstream in;
ofstream out;
class Expresion
{
	string E;
	inline int priority( char );
	string transform();
	void getvalue();
public:
	int solve();
	friend inline istream& operator>>( istream&, Expresion& );
};
inline int Expresion::priority( char x )
{
	if( '(' == x )
		return 0;
	if( '+' == x || '-' == x )
		return 1;
	if( '*' == x || '/' == x || '%' == x )
		return 2;
	if( '^' == x )
		return 3;
	if( ')' == x )
		return 4;
	return -1;
}
string Expresion::transform()
{int p;
 stack<char> s;
 string t;
 string::const_iterator it=E.begin(), iend=E.end();
	while( it < iend )
	{
		if( *it >= '0' && *it <= '9' )
		{
			while( it < iend && *it >= '0' && *it <= '9' )
				t.push_back(*it), ++it;
			t.push_back(' ');
			continue;
		}
		if( '(' == *it )
		{
			s.push(*it);
			++it;
			continue;
		}
		if( ')' == *it )
		{++it;
			while( !s.empty() && '(' != s.top() )
				t.push_back(s.top()), s.pop();
			if( !s.empty() )
				s.pop();
			continue;
		}
		p=priority(*it);
		while( !s.empty() && p <= priority(s.top()) )
			t.push_back(s.top()), s.pop();
		s.push(*it);
		++it;
	}
	while( !s.empty() )
		t.push_back(s.top()), s.pop();
	return t;
}
int Expresion::solve()
{E=transform();
	int a, b, number;
	stack<int> v;
	string::const_iterator it=E.begin(), iend=E.end();
	while( it < iend )
	{
		if( *it >= '0' && *it <= '9' )
		{number=0;
			while( it < iend && *it >= '0' && *it <= '9' )
				number=number*10+*it-'0', ++it;
			v.push(number); 	
			if( it < iend ) 
				++it;
			continue;
		}
		b=v.top(); v.pop(); a=v.top(); v.pop();
		switch( *it )
		{
			case '+' : v.push(a+b); break;
			case '-' : v.push(a-b); break;
			case '*' : v.push(a*b); break;
			case '/' : v.push(a/b); break;
			case' %' : v.push(a%b); break;
			case '^' : v.push( (int)powl( (int)a, (int)b ) ); break;
		}
		++it;
	}
	return v.top();
}
inline istream& operator>>( istream& in, Expresion& s )
{
	in>>s.E;
	return in;
}
int main()
{Expresion expresion;
	in.open(InFile);
	in>>expresion;
	out.open(OutFile);
	out<<expresion.solve();
	return 0;
}