Cod sursa(job #2399963)

Utilizator RaresLiscanLiscan Rares RaresLiscan Data 8 aprilie 2019 11:04:06
Problema Bool Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.41 kb
#include <bits/stdc++.h>

using namespace std;

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

string str, p;
stack <int> s;
stack <bool> S;
bool v[50];

int priority (char chr)
{
    if (chr == '!') return 3;
    if (chr == '&') return 2;
    if (chr == '|') return 1;
    return 0;
}

void polishNotation (int n)
{
    for (int i = 0; i < n; i ++) {
        if (str.substr(i, 2) == "OR") p += '|', i ++;
        else if (str.substr(i, 3) == "AND") p += '&', i += 2;
        else if (str.substr(i, 4) == "TRUE") p += '1', i += 3;
        else if (str.substr(i, 4) == "FALSE") p += '1', i += 3;
        else if (str.substr(i, 3) == "NOT") p += '!', i += 2;
        else if (str[i] != ' ') p += str[i];
    }
    str = p;
    p.clear();
    n = str.size();
    for (int i = 0; i < n; i ++) {
        if (priority(str[i]) != 0) {
            while (!s.empty() && priority(str[s.top()]) > priority(str[i]) && str[s.top()] != '(') {
                p += str[s.top()], s.pop();
            }
            s.push(i);
        }
        else if (str[i] == '(') s.push(i);
        else if (str[i] == ')') {
            while (!s.empty() && str[s.top()] != '(') p += str[s.top()], s.pop();
            if (!s.empty() && str[s.top()] == '(') s.pop();
        }
        else p += str[i];
    }
    while (!s.empty()) p += str[s.top()], s.pop();
    str = p;
}

bool chrToBool (char chr)
{
    if (chr == '1') return true;
    if (chr == '0') return false;
    if (isalpha(chr)) return v[chr - 'A'];
}

bool evaluare ()
{
    while (!S.empty()) S.pop();
    int n = str.size();
    for (int i = 0; i < n; i ++) {
        if (priority(str[i]) == 0) S.push(chrToBool(str[i]));
        else if (priority(str[i]) != 3) {
            bool o1, o2, res = 0;
            o1 = S.top(), S.pop();
            o2 = S.top(), S.pop();
            if (str[i] == '&') res = (o1&o2);
            else if (str[i] == '|') res = (o1|o2);
            S.push(res);
        }
        else if (priority(str[i]) == 3) {
            bool op = S.top();
            S.pop();
            S.push(!op);
        }
    }
    return S.top();
}

int main()
{
    getline(fin, str);
    polishNotation(str.size());
    int n;
    fin >> n;
    char chr;
    p.clear();
    for (int i = 0; i < n; i ++) {
        fin >> chr;
        v[chr - 'A'] = !v[chr - 'A'];
        fout << evaluare();
    }
    return 0;
}