Cod sursa(job #478759)

Utilizator BitOneSAlexandru BitOne Data 20 august 2010 12:09:17
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
/* 
 * File:   main.cpp
 * Author: bitone
 *
 * Created on August 20, 2010, 11:46 AM
 */
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

/*
 * 
 */
typedef signed int sint;
inline sint Priority( char x )
{
    if( '+' == x || '-' == x )
        return 1;
    if( '*' == x || '/' == x )
        return 2;
    if( '^' == x )
        return 3;
    return -1;
}
void Transform( string& expresion )
{
    sint p;
    string t;
    string::const_iterator it=expresion.begin(), iend=expresion.end();
    stack< char > s;
    for( ; it < iend; )
    {
        if( *it >= '0' && *it <= '9' )
        {
            for( ; *it >= '0' && *it <= '9' && it < iend; ++it )
                t.push_back(*it);
            t.push_back('}');
        }
        else if( '(' == *it )
                s.push(*it), ++it;
             else if( ')' == *it )
                  {
                        for( ++it; '(' != s.top(); t.push_back( s.top() ), s.pop() );
                        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() );
    expresion=t;
}
sint Evaluate( string& expresion )
{
    Transform( expresion );
    stack< sint > s;
    sint number, a, b;
    string::const_iterator it=expresion.begin(), iend=expresion.end();
    for( ; it < iend; ++it )
    {
        if( *it >= '0' && *it <= '9' )
        {
            for( number=0; *it >= '0' && *it <= '9'; ++it )
                number=number*10+*it-'0';
            s.push(number);
        }
        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);
                }
             }
    }
    return s.top();
}
int main(int argc, char** argv)
{
    string expresion;
    ifstream in( "evaluare.in" );
    getline( in, expresion );
    ofstream out( "evaluare.out" );
    out<<Evaluate( expresion )<<'\n';
    return EXIT_SUCCESS;
}