Cod sursa(job #1131071)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 28 februarie 2014 17:37:16
Problema Evaluarea unei expresii Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.36 kb
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define N_MAX (int)1e5
char S[ N_MAX + 2 ];
int N, sp;

/*
    Syntax:
    expr: term [ '+|-' + term ]*
    term: fact [ '*|/' + fact ]*
    fact: '(' + expr + ')' | num
*/

int expr( );
int term( );
int fact( );
int num( );

int expr( ) {
    int ans = term( );
    while( S[ sp ] == '+' || S[ sp ] == '-' ) {
        if( S[ sp ] == '+' ) {
            sp ++;
            ans += term( );
        } else {
            sp ++;
            ans -= term( );
        }
    }
    return ans;
}

int term( ) {
    int ans = fact( );
    while( S[ sp ] == '*' || S[ sp ] == '/' ) {
        if( S[ sp ] == '*' ) {
            sp ++;
            ans *= fact( );
        } else {
            sp ++;
            ans /= fact( );
        }
    }
    return ans;
}

int fact( ) {
    int ans = 0;
    if( S[ sp ] == '(' ) {
        sp ++;
        ans = expr( );
        sp ++;
    } else {
        ans = num( );
    }
    return ans;
}

int num( ) {
    int ans = 0;
    while( isdigit( S[ sp ] ) ) {
        ans = ans * 10 + S[ sp ++ ] - '0';
    }
    return ans;
}

int main( ) {
    FILE * fin, * fout;
    fin = fopen( "evaluare.in", "r" );
    fout = fopen( "evaluare.out", "w" );

    fgets( S, sizeof( S ), fin );
    N = strlen( S ) - 1;
    printf( "%d\n", N );

    fprintf( fout, "%d\n", expr( ) );

    fclose( fin );
    fclose( fout );
}