Cod sursa(job #1480193)

Utilizator Burbon13Burbon13 Burbon13 Data 2 septembrie 2015 11:12:44
Problema Evaluarea unei expresii Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <string>
using namespace std;

ifstream f("evaluare.in");
ofstream o("evaluare.out");

const int nmx = 100005;

string s;

inline int numar(const int st, const int dr) {
    static int aux;
    aux = 0;
    for(int i = st; i <= dr; ++i) {
        aux *= 10;
        aux += (int)s[i] - 48;
    }
    return aux;
}

int eval(int st, int dr) {

    static int parant;

    while(s[st] == '(' && s[dr] == ')') {
        ++ st;
        -- dr;
    }

    parant = 0;
    for(int i = dr; i >= st; --i) {
        if(s[i] == ')')
            ++ parant;
        else if(s[i] == '(')
            -- parant;
        if(s[i] == '+' && not parant)
            return eval(st,i-1) + eval(i+1,dr);
        else if(s[i] == '-' && not parant)
            return eval(st,i-1) - eval(i+1,dr);
    }

    parant = 0;
    for(int i = dr; i >= st; --i) {
        if(s[i] == ')')
            ++ parant;
        else if(s[i] == '(')
            -- parant;
        if(s[i] == '*' && not parant)
            return eval(st,i-1) * eval(i+1,dr);
        else if(s[i] == '/' && not parant)
            return eval(st,i-1) / eval(i+1,dr);
    }

    return numar(st,dr);
}

int main() {

    f >> s;
    o << eval(0,s.size()-1);

    return 0;
}