Cod sursa(job #434594)

Utilizator alexandru92alexandru alexandru92 Data 6 aprilie 2010 09:07:57
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.26 kb
/* 
 * File:   main.cpp
 * Author: VirtualDemon
 *
 * Created on April 6, 2010, 8:49 AM
 */
#include <stack>
#include <string>
#include <cstdlib>
#include <fstream>

/*
 * 
 */
using namespace std;
inline int priority( char x )
{
    if( '(' == x )
        return 0;
    if( '+' == x || '-' == x )
        return 1;
    if( '*' == x || '/' == x )
        return 2;
    return 5;
}
inline string transform( string* expresion )
{
    int p;
    stack< char > v;
    string transform;
    string::const_iterator it=expresion->begin(), iend=expresion->end();
    while( it < iend )
    {
        if( *it >= '0' && *it <= '9' )
        {
            for( ; *it >= '0' && *it <= '9' && it < iend; ++it )
                transform.push_back(*it);
            transform.push_back(' ');
            continue;
        }
        if( '(' == *it )
        {++it;
            v.push('(');
            continue;
        }
        if( ')' == *it )
        {
            for( ++it; '(' != v.top(); v.pop() )
                transform.push_back(v.top());
            v.pop();
            continue;
        }
        p=priority( *it );
        for( ; !v.empty() && p <= priority( v.top() ); v.pop() )
            transform.push_back(v.top());
        v.push(*it);
        ++it;
    }
    for( ; !v.empty(); transform.push_back(v.top()), v.pop() );
    return transform;
}
inline int evaluate( string* expresion )
{
    stack< int > v;
    int number, a, b;
    *expresion=transform( expresion );
    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';
            v.push(number);
            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;
        }
    }
    return v.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;
}