Cod sursa(job #2562824)

Utilizator Teo_1101Mititelu Teodor Teo_1101 Data 29 februarie 2020 18:23:21
Problema Bool Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.63 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1005;

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

stack < bool > V;
stack < char > O;

char E[NMAX], C[NMAX];
bool B[30];
int N;

void Read()
{
    fin.getline( E, NMAX-4 );
    fin >> N >> C;
}
bool NOT( bool x )
{
    if( x == 0 ) return 1;
    return 0;
}
bool ApplyOp(bool x, bool y, char op )
{
    switch(op)
    {
    case 'n':
    {
        V.push(x);
        return NOT(y);
    }
    case 'a':
        return x && y;
    case 'o':
        return x || y;
    }
}
int Priority( char c )
{
    if( c == 'n' ) return 3;
    if( c == 'a' ) return 2;
    if( c == 'o' ) return 1;
    return 0;
}
void Exp()
{
    for( int i = 0; E[i]; ++i )
    {
        //cout << E[i] << ' ';
        if( E[i] == ' ' )continue;
        if( E[i] == '(' )
        {
            O.push(E[i]);
            continue;
        }
        if( E[i] >= 'A' && E[i] <= 'Z' && !(E[i+1] >= 'A' && E[i+1] <= 'Z' ) )
        {
            bool x = B[E[i]-'A'];
            V.push( x );

        }
        else if( strncmp( E+i, "TRUE", 4 ) == 0 ) {V.push( 1 ); i+=3;}
        else if( strncmp( E+i, "FALSE", 5 ) == 0 ) {V.push( 0 ); i+=4;}
        else if( E[i] == ')' )
        {
            while( O.size() && O.top() != '(' )
            {
                bool val1 = V.top();
                V.pop();
                bool val2 = V.top();
                V.pop();

                V.push( ApplyOp( val2, val1, O.top() ) );
                O.pop();
            }
            if( O.size() ) O.pop();
        }
        else
        {
            char op;
            if( strncmp( E+i, "NOT", 3 ) == 0 ) {op = 'n'; i+=2;}
            else if( strncmp( E+i, "AND", 3 ) == 0 ) {op = 'a'; i+=2;}
            else if( strncmp( E+i, "OR", 2 ) == 0 ) {op = 'o'; i++;}

            while( O.size() && Priority( O.top() ) >= Priority( op ) )
            {
                bool val1 = V.top();
                V.pop();
                bool val2 = V.top();
                V.pop();

                V.push( ApplyOp( val2, val1, O.top() ) );
                O.pop();
            }
            O.push( op );

        }
    }
    while( O.size() )
    {
        bool val1 = V.top();
        V.pop();
        bool val2 = V.top();
        V.pop();

        V.push( ApplyOp( val2, val1, O.top() ) );
        O.pop();
    }

    fout << V.top();
    V.pop();
}

void Solve()
{
    for( int i = 0; i < N; ++i )
    {
        B[C[i]-'A'] = NOT(B[C[i]-'A']);

        Exp();
    }
}
int main()
{
    Read();
    Solve();
    return 0;
}