Cod sursa(job #1975489)

Utilizator MaligMamaliga cu smantana Malig Data 1 mai 2017 08:43:17
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");

#define pb push_back
const int strMax = 1e6 + 5;
const int lvlMax = 2;
const char lvlOp[2][3] = {'+','-','\0','*','/','\0'};

int N;
char str[strMax],*p;

int eval(int);
int compute(int,int,char);

int main() {
    in>>(str);
    p = str;

    out<<eval(0)<<'\n';

    in.close();out.close();
    return 0;
}

int eval(int lvl) {
    int ans = 0;
    if (lvl == lvlMax) {
        if (*p == '(') {
            ++p;
            ans = eval(0);
            ++p;
        }
        else {
            while ('0' <= *p && *p <= '9') {
                ans = ans * 10 + *p++ - '0';
            }
        }
    }
    else {
        for (ans = eval(lvl+1); *p != '\0' && strchr(lvlOp[lvl],*p) != nullptr; ) {
            char op = *p++;
            ans = compute(ans,eval(lvl+1),op);
        }
    }
    return ans;
}

int compute(int x,int y,char op) {
    switch (op) {
    case '+': return x + y;
    case '-': return x - y;
    case '*': return x * y;
    case '/': return x / y;
    }
}