Cod sursa(job #3291526)

Utilizator alexscanteieScanteie Alexandru alexscanteie Data 5 aprilie 2025 00:10:40
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>

using namespace std;

#define ll long long
#define hmax 2
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

string s;
long long pos = 0;
char operand[4][4] = { "+-", "*/", "^", "" };

long operatie(long x, long y, char c) {
    switch (c) {
        case '+': return x + y;
        case '-': return x - y;
        case '*': return x * y;
        case '/': return x / y;
    }
    return 0;
}

long element();

long eval(long h) {
    long r = (h == hmax) ? element() : eval(h + 1);
    while (pos < s.length() && strchr(operand[h], s[pos]))
        r = operatie(r, eval(h + 1), s[pos++]);
    return r;
}

long element() {
    ll r = 0;
    if (s[pos] == '(') {
        ++pos;
        r = eval(0);
        ++pos;
    } else {
        while (pos < s.length() && isdigit(s[pos]))
            r = r * 10 + (s[pos++] - '0');
    }
    return r;
}



int main() {
    getline(fin, s);
    fout << eval(0) << '\n';

    return 0;
}