Cod sursa(job #459827)

Utilizator BitOneSAlexandru BitOne Data 31 mai 2010 12:26:15
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.42 kb
#include <stack>
#include <string>
#include <cstdlib>
#include <fstream>

/*
 *
 */
 using namespace std;
 string expresion, t;
 inline int priority( char x )
 {
     if( '(' == x )
        return 0;
     if( '+' == x || '-' == x )
        return 1;
     if( '*' == x || '/' == x )
        return 2;
     if( ')' == x )
        return 3;
     return 5;
 }
 void transform( void )
 {
     int p;
     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 )
                   {
                       for( ++it; '(' != s.top(); s.pop() )
                            t.push_back( s.top() );
                        s.pop();
                   }
                   else {
                            for( p=priority( *it ); !s.empty() && p <= priority(s.top()); s.pop() )
                                t.push_back(s.top());
                            s.push(*it);
                            ++it;
                        }
     }
     for( ; !s.empty(); s.pop() )
        t.push_back(s.top());
 }
 int eval( void )
 {
     int n, a, b;
     stack< int > s;
     transform();
     string::const_iterator it=t.begin(), iend=t.end();
     for( ; it < iend; ++it )
     {
         if( *it >= '0' && *it <= '9' )
         {
             for( n=0; *it >= '0' && *it <= '9'; ++it )
                n=n*10+*it-'0';
             s.push(n);
         }
         else {
                    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); break;
                    }
              }
     }
     return s.top();
 }
 int main( void )
 {
     ifstream in( "evaluare.in" );
     getline( in, expresion, '\n' );
     ofstream out( "evaluare.out" );
     out<<eval()<<'\n';
     return EXIT_SUCCESS;
 }