Cod sursa(job #1877626)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 13 februarie 2017 16:52:20
Problema Bool Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.08 kb
#include <fstream>

using namespace std;

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

const int omega = 26;
bool val[omega + 1];

string s, q;
int pos, n;

int expr(), term(), getval();

inline int ind (char x) {
    return x - 'A' + 1;
}

inline bool Or() {
    if (pos + 1 < n)
        return (s[ pos ] == 'O' && s[pos + 1] == 'R');
    return 0;
}

inline bool Not() {
    if (pos + 2 < n)
        return (s[ pos ] == 'N' && s[pos + 1] == 'O' && s[pos + 2] == 'T');
    return 0;
}

inline bool And() {
    if (pos + 2 < n)
        return (s[ pos ] == 'A' && s[pos + 1] == 'N' && s[pos + 2] == 'D');
    return 0;
}

inline bool True() {
    if (pos + 3 < n)
        return (s[ pos ] == 'T' && s[pos + 1] == 'R' && s[pos + 2] == 'U' && s[pos + 3] == 'E');
    return 0;
}

inline bool False() {
    if (pos + 4 < n)
        return (s[ pos ] == 'F' && s[pos + 1] == 'A' && s[pos + 2] == 'L' && s[pos + 3] == 'S' && s[pos + 4] == 'E');
    return 0;
}

int getval() {
    bool ok = 1;

    if (Not()) {
        ok = 0;
        pos += 4;
    }

    int ans;
    if (s[ pos ] == '(') {
        ++ pos;
        ans = expr();
    } else if (True()) {
        ans = 1;
        pos += 4;
    } else if (False()) {
        ans = 0;
        pos += 5;
    } else if (Not()) {
        pos += 4;
        ans = getval();
    } else {
        ans = val[ ind(s[ pos ]) ];
        ++ pos;
    }

    while (pos < n && s[ pos ] == ' ') {
        ++ pos;
    }

    if (ok == 0) ans = !ans;
    return ans;
}

int expr() {
    int ans = term();
    while (pos < n && Or()) {
        pos += 3;
        ans |= term();
    }

    if (s[ pos ] == ')') {
        ++ pos;
    }
    return ans;
}

int term() {
    int ans = getval();
    while (pos < n && And()) {
        pos += 4;
        ans &= getval();
    }
    return ans;
}

int main() {
    getline(fin, s);
    n = (int)s.size();

    int nq;
    fin >> nq >> q;
    for (int i = 0; i < nq; ++ i) {
        int x = ind( q[ i ] );
        val[ x ] = !val[ x ];

        pos = 0;
        fout << expr();
    }

    fout << "\n";

    fin.close();
    fout.close();
    return 0;
}