Cod sursa(job #1850355)

Utilizator RobybrasovRobert Hangu Robybrasov Data 18 ianuarie 2017 16:24:52
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <cstdio>
#include <cstring>
#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;
}

const char signs[3][3] = { "+-", "*/", "" };

/*
 * 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 < 2) {
        res = eval(p, l + 1);
        while (strchr(signs[l], *p))
            switch (*p) {
                case '+': res += eval(++p, l + 1); break;
                case '-': res -= eval(++p, l + 1); break;
                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);
            ++p;
        }
        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;
}