Cod sursa(job #698982)

Utilizator predator5047Butiu Alexandru Octavian predator5047 Data 29 februarie 2012 17:05:26
Problema Bool Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.19 kb
#include <iostream>
#include <fstream>
#include <string>
#define H(C) ((C) - 64)

bool v[30];
std::string exp;
std::string::iterator it;
void transform(std::string& aux);
bool eval();
bool termen();
bool factor();

int main()
{
    char c;
    int n;
    std::string aux;

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

    getline(fin,aux);

    transform(aux);


    fin >> n;
    getline(fin,aux);

    std::cout << exp;

    for(; n; --n)
    {
        c = fin.get();
        v[H(c)] = !v[H(c)];
        it = exp.begin();
        fout << eval();
    }

    fin.close();
    fout.close();


    return 0;
}

bool eval()
{
    bool r = termen();
    while(*it == '|')
    {
        ++it;
        r |= termen();
    }
    return r;
}

bool termen()
{
    bool r = factor();

    while(*it == '&')
    {
        ++it;
        r &= factor();
    }

    return r;
}

bool factor()
{
    bool r = false;

    if(*it == '!')
    {
        ++it;

        r = !factor();

    }
    else if(*it == '(')
    {
        ++it;
        r = eval();
        ++it;
    }
    else
    {
        if(*it == '0' || *it == '1')
            r = *it - '0';
        else
            r = v[H(*it)];
        ++it;
    }

    return r;
}

void transform(std::string& aux)
{
    for(int i = 0; i < aux.size(); )
    {
        if(aux[i] == ' ')
        {
            ++i;
            continue;
        }
        if(aux[i] == 'A' && aux.substr(i,3) == "AND")
        {
            exp += '&';
            i += 3;
        }
        else if(aux[i] == 'T' && aux.substr(i,4) == "TRUE")
        {
            exp += '1';
            i += 4;
        }
        else if(aux[i] == 'F' && aux.substr(i,5) == "FALSE")
        {
            exp += '0';
            i += 5;
        }
        else if(aux[i] == 'N' && aux.substr(i,3) == "NOT")
        {
            exp += '!';
            i += 3;
        }
        else if(aux[i] == 'O' && aux.substr(i,2) == "OR")
        {
            exp += '|';
            i += 2;
        }
        else
        {
            exp += aux[i];
            ++i;
        }
    }
}