Cod sursa(job #1701193)

Utilizator CTI_KnightCir Constantin CTI_Knight Data 12 mai 2016 13:41:56
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
# include <fstream>
# include <iostream>
# include <algorithm>
# include <stack>
# include <string>

using namespace std;

ifstream f ( "evaluare.in" );
ofstream g ( "evaluare.out" );

int i = 0;
string s;
stack < int > st;
stack < char > sto;

void evaluare() {

    int n = 0;
    while ( s[i] <= '9' && s[i] >= '0' ) {
        n = n * 10 + ( s[i] - '0' );
        ++ i;
    }
    st.push( n );
    -- i;
}

void calcul(){

    int y = st.top(); st.pop();
    int x = st.top(); st.pop();
    char op = sto.top(); sto.pop();

    if ( op == '+' ) st.push( x + y );
    else if ( op == '-' ) st.push( x - y );
    else if ( op == '*' ) st.push( x * y );
    else if ( op == '/' ) st.push( x / y );
}

int main()
{
    f >> s;
    vector < int > p( 260, 0 );
    p['+'] = 1;
    p['-'] = 1;
    p['*'] = 2;
    p['/'] = 2;

    for ( ; i < s.size(); ++ i ) {

        if ( s[i] >= '0' && s[i] <= '9' ) { evaluare();}
        else if ( s[i] == '(' ) sto.push( '(' );
        else if ( s[i] == ')' ) {
            while ( !sto.empty() && sto.top() != '(' )
                calcul();
            sto.pop();
        }
        else {
            while( !sto.empty() && p[ s[i] ] <= p[sto.top()] )
                calcul();
            sto.push( s[i] );
        }
    }

    while ( !sto.empty() )
        calcul();

    g << st.top();

    return 0;
}