Cod sursa(job #2399868)

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

using namespace std;

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

string str, p;
stack <int> 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.push_back('|'), i ++;
        else if (str.substr(i, 3) == "AND") p.push_back('&'), i += 2;
        else if (str.substr(i, 4) == "TRUE") p.push_back('1'), i += 3;
        else if (str.substr(i, 4) == "FALSE") p.push_back('0'), i += 3;
        else if (str.substr(i, 3) == "NOT") p.push_back('!'), i += 2;
        else if (str[i] != ' ') p.push_back(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])) {
                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()) 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;
    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;
            o1 = s.top(), s.pop();
            o2 = s.top(), s.pop();
            if (str[i] == '&') s.push(o1 && o2);
            else if (str[i] == '|') s.push(o1 || o2);
        }
        else {
            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;
    for (int i = 0; i < n; i ++) {
        fin >> chr;
        v[chr - 'A'] = !v[chr - 'A'];
        fout << evaluare();
    }
    return 0;
}