Cod sursa(job #613182)

Utilizator BitOneSAlexandru BitOne Data 17 septembrie 2011 20:56:42
Problema Evaluarea unei expresii Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.48 kb
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;
typedef string::const_iterator csIt;
string expresion, texpresion;
inline int priority( char op )
{
    switch( op )
    {
        case '+' : ;
        case '-' : return 0;
        case '*' : ;
        case '/' : return 1;
        case '^' : return 2;
        case ')' : return 3;
        default  : return -5;
    }
}
void transform()
{
    int p;
    stack<char> s;
    csIt it=expresion.begin(), iend=expresion.end();
    while( it < iend )
    {
        if( *it >= '0' && *it <= '9' )
        {
            for( ; it < iend && *it >= '0' && *it <= '9'; ++it )
                texpresion.push_back(*it);
            texpresion.push_back('?');
        }
        else if( '(' == *it )
                s.push('('), ++it;
              else if( ')' == *it )
                   {
                       for( ++it; '(' != s.top(); s.pop() )
                            texpresion.push_back( s.top() );
                   }
                   else {
                            p=priority(*it);
                            for( ; !s.empty() && priority(s.top()) >= p; s.pop() )
                                texpresion.push_back( s.top() );
                            s.push(*it);
                            ++it;
                        }
    }
    for( ; !s.empty(); texpresion.push_back( s.top() ), s.pop() );
}
int ExpresionEvaluate()
{
    transform();
    char op;
    int a, b;
    stack<int> s;
    csIt it=texpresion.begin(), iend=texpresion.end();
    for( ; it < iend; ++it )
    {
        if( *it >= '0' && *it <= '9' )
        {
            for( a=0; it < iend && *it >= '0' && *it <= '9'; ++it )
                a=a*10+*it-'0';
            s.push(a);
        }
        else if( priority(*it) >= 0 && priority(*it) <= 2 )
             {
                 op=*it;
                 b=s.top(); s.pop();
                 a=s.top(); s.pop();
                 switch( op )
                 {
                     case '+' : s.push(a+b); break;
                     case '-' : s.push(a-b); break;
                     case '*' : s.push(a*b); break;
                     case '/' : s.push(a/b); break;
                 }
             }
    }
    return s.top();
}
int main( void )
{
    ifstream in( "evaluare.in" );
    getline( in, expresion );
    ofstream out( "evaluare.out" );
    out<<ExpresionEvaluate()<<'\n';
    return EXIT_SUCCESS;
}