Cod sursa(job #2923206)

Utilizator CookieDaggerDragan Iulian CookieDagger Data 12 septembrie 2022 10:32:40
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.47 kb
#include <string>
#include <fstream>
#include <vector>

using namespace std;

struct op{
    int operation;
    int index;
    op(int p_operation, int p_index): operation(move(p_operation)), index(move(p_index)){}
};

ifstream cin("evaluare.in");
ofstream cout("evaluare.out");

string operations = "+-*/";

string trimBraces(string s){
    if(s.length() < 2) return s;
    if(s[0] == '(' && s[s.length() - 1] == ')'){
        cout<<s<<" devine "<<s.substr(1, s.length()-2)<<"\n";
        return s.substr(1, s.length()-2);
    }
    return s;
}

int swOp(int a, int b, int op){
    if(op == 0){
        return a + b;
    }
    if(op == 1){
        return a - b;
    }
    if(op == 2){
        return a * b;
    }
    if(op == 3){
        return a / b;
    }
    else return 69;
}

int counter = 0;

int eval(string s) {
    s = trimBraces(s); 
    cout<<"recursion #"<<counter<<" "<<s<<endl;
    counter++;
    int nested = 0;
    bool secondDegree = true;
    vector<op> opQueue;
    for(int i=0; i<s.length(); i++) {
        char c = s[i];
        if(c == '(') {
            nested++;
            cout<<"nested++";
            continue;
        } else if(c == ')') {
            nested--;
            cout<<"nested--";
            continue;
        }
        if(nested == 0){
            int found = operations.find(c);
            if(found != string::npos){
                if(found<=1){
                    if(secondDegree){
                        opQueue.clear();
                        secondDegree = false;
                    }
                    opQueue.emplace_back(found, i);
                }
                else if(secondDegree){
                    opQueue.emplace_back(found, i);
                }
            }
        }
    }
    if(opQueue.empty()){
        try{
            return stoi(s);
        }catch(exception e){
            cout<<"\""<<s<<"\"";
        }
    }
    for(auto it:opQueue){
        cout<<it.index<<" "<<it.operation;
    }
    int currRes = eval((s.substr(0, opQueue[0].index)));
    for(int i = 0; i < opQueue.size() - 1; i++){
        currRes = swOp(currRes, eval((s.substr(opQueue[i].index + 1, opQueue[i+1].index-opQueue[i].index-1))), opQueue[i].operation);
    }
    currRes = swOp(currRes, eval((s.substr(opQueue.back().index + 1, s.length()))), opQueue.back().operation);
    return currRes;
}

int main()
{
    string a;
    cin>>a;
    cout<<eval((a));
    return 0;
}