Cod sursa(job #1268372)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 20 noiembrie 2014 21:31:59
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

const int Lmax = 1e5 + 1;

char *p;
char s[Lmax];

char op[2][4] = { "+-", "*/" };
const int Hmax = 2;

int operatie( int a, int b, char c )
{
    switch( c )
    {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;

        default: return 0;
    }

    return 0;
}

int solve( int );

int termen()
{
    int t = 0;

    if ( *p == '(' )
    {
        p++;
        t = solve( 0 );
        p++;
    }
    else
    {
        while ( isdigit( *p ) )
        {
            t = t * 10 + *p - '0';
            p++;
        }
    }

    return t;
}

int solve( int h )
{
    int t = 0;

    if ( h == Hmax )
        t = termen();
    else
        t = solve( h + 1 );

    while ( strchr( op[h], *p ) )
        t = operatie( t, solve( h + 1 ), *p++ );

    return t;
}


void citire(){

    freopen("evaluare.in", "r", stdin);

    fgets( s, Lmax, stdin );

    p = s;
}

void afis(){

    freopen("evaluare.out", "w", stdout);

    printf("%d\n", solve( 0 ));
}

int main()
{
    citire();
    afis();

    return 0;
}