Cod sursa(job #1850327)

Utilizator RobybrasovRobert Hangu Robybrasov Data 18 ianuarie 2017 15:47:51
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <cstdio>
#define MAX_S 100000

using namespace std;

char L[MAX_S];

int readNumber(char* &p) {
    int n = 0;
    for (; *p >= '0' && *p <= '9'; ++p)
        n = 10 * n + *p - '0';
    return n;
}

/*
 * p - the character we're currently on
 * l - the type of term we're currently examining:
 *     - 0 is a sum
 *     - 1 is a product
 *     - 2 is either a token (i.e. a number or variable) or a parenthesis
 * This function can also be viewed as a multi-purpose function, it's "mode of
 * operation" being set by the value of l. This function is thus nothing more
 * than the trivial combination of the functionalities of the three functions in
 * the indirect recursive implementation.
 */
int eval(char* &p, int l) {
    int res = 0;
    if (l == 0) { // Compute the sum of product terms
        res = eval(p, l + 1);
        while (*p == '+' || *p == '-')
            switch (*p) {
                case '+': res += eval(++p, l + 1); break;
                case '-': res -= eval(++p, l + 1); break;
            }
        ++p;
    } else if (l == 1) { // Compute the products of tokens (or parentheses) here
        res = eval(p, l + 1);
        while (*p == '*' || *p == '/')
            switch (*p) {
                case '*': res *= eval(++p, l + 1); break;
                case '/': res /= eval(++p, l + 1); break;
            }
    } else // Compute the value of a token, which is either a number or a parenthesis
        if (*p == '(')
            res = eval(++p, 0);
        else
            res = readNumber(p);
    return res;
}

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

    fprintf(fout, "%d", eval(p, 0));

    return 0;
}