Cod sursa(job #1907512)

Utilizator VicktorVictor Teodor Stoian Vicktor Data 6 martie 2017 19:37:45
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <cstdio>
#include <cstring>

using namespace std;

ifstream cin("evaluare.in");
ofstream cout("evaluare.out");

struct node{

    int val;
    char op;
    node *l,*r;
    node( int a = 0, char b = 0, node *c = 0, node *d = 0 ) :
        val(a), op(b), l(c), r(d) {}
}*Rad;

char op[4][20]={"+-","*/","^"};
int nr;
char *p,s[100005];

inline node *expr( int lev ) {
    node *x, *y;

    if( lev == 2 )
        if( *p == '(' )
            ++p, x = expr(0), ++p;
        else
            for( x = new node(); *p >= '0' && *p <= '9'; ++p )
                x->val = x->val * 10 + *p - '0';
    else
        for( x = expr( lev+1 ); strchr( op[lev], *p ); x = y )
            y = new node( 0, *p++, x, expr( lev+1 ) );
    return x;
}

inline int eval(node *n){
    switch( n->op ) {
        case '+': return eval( n->l ) + eval( n->r );
        case '-': return eval( n->l ) - eval( n->r );
        case '*': return eval( n->l ) * eval( n->r );
        case '/': return eval( n->l ) / eval( n->r );
        default: return n->val;
    }
}

/*inline void in_ord(node *k){
    if(k->l)
        in_ord(k->l);
    if(k->r)
        in_ord(k->r);
    if(k->val)
        printf("%d ", k->val);
    else
        printf("%c ", k->op);
}
*/
int main(){
   // FILE*cin=freopen("evaluare.in","r",stdin);
    //scanf("%s",&s);
   cin.getline(s,100005);
    p=s;
    p[strlen(p)]='\n';
    Rad=expr(0);
    cout<<eval(Rad);
   // in_ord(Rad);
    return 0;
}