Cod sursa(job #2852817)

Utilizator Matei_MunteanuMunteanu Matei Ioan Matei_Munteanu Data 19 februarie 2022 16:43:57
Problema Bool Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.33 kb
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

ifstream fin("bool.in");
ofstream fout("bool.out");

string expression, input;
int n, index;
bool variables[30];

bool elementAND();
bool elementNOT();
bool element();

// will handle the content of an expression/subexpression - which consists of element of an OR expression
bool evaluate() {
    bool result = elementAND();
    while (expression.substr(index, 2) == "OR") {
        index += 2;
        bool next = elementAND();
        result = result || next;
    }
    return result;
}

// will handle the content of an element - which consists of element of an AND expression
bool elementAND() {
    bool result = elementNOT();
    while (expression.substr(index, 3) == "AND") {
        index += 3;
        bool next = elementNOT();
        result = result && next;
    }
    return result;
}

// will handle the content of an element - which can be a expression or a NOT expression
bool elementNOT() {
    if (expression.substr(index, 3) == "NOT") {
        index += 3;
        return !elementNOT();
    }
    return element();
}

// will return the value of a single element (variable or constant), which in turn can be a subexpression
bool element() {
    bool result;
    if (expression[index] == '(') { // we have a subexpression
        index ++;                   // we go over '('
        result = evaluate();        // evaluate the subexpression
        index ++;                   // we go over ')'
        return result;
    }
    // case TRUE
    if (expression.substr(index, 4) == "TRUE") {
        index += 4;
        return true;
    }
    // case FALSE
    if (expression.substr(index, 5) == "FALSE") {
        index += 5;
        return false;
    }
    // case variable
    char variable = expression[index];
    result = variables[variable - 'A'];
    index ++;
    return result;
}

void removeSpaces() {
    for(int i = 0; i < expression.size(); i ++) {
        if (expression[i] == ' ')
            expression.erase(i, 1);
    }
}

int main()
{
    getline(fin, expression);
    fin >> n;
    fin >> input;
    removeSpaces();
    for (auto variable : input) {
        variables[variable - 'A'] = !variables[variable - 'A'];
        fout << evaluate();
        index = 0;
    }
    return 0;
}