Cod sursa(job #2047298)

Utilizator cipri321Marin Ciprian cipri321 Data 24 octombrie 2017 18:34:34
Problema Bool Scor 60
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.81 kb
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
ifstream fi("bool.in");
ofstream fo("bool.out");
int n;
string input,schimb;
vector<int> s;
int V[30];
map<string,pair<int,int> > OP;
map<string,int> COD;
void initOP()
{
    OP["NOT"]={3,1},OP["AND"]={2,1},OP["OR"]={1,1};
    COD["NOT"]=-1,COD["AND"]=-2,COD["OR"]=-3;
}
bool litera(char c)
{
    return 'A'<=c&&c<='Z';
}
bool oper(string s)
{
    return s=="NOT"||s=="AND"||s=="OR";
}
int truefalse(string s)
{
    if(s=="TRUE")
        return 1;
    if(s=="FALSE")
        return 0;
    return -1;
}
vector<int> rpn(string s)
{
    string crt;
    vector<int> rez;
    stack<string> S;
    for(auto c:s)
    {
        if(litera(c))
            crt+=c;
        else
        {
            if(crt!=""&&truefalse(crt)!=-1)
            {
                rez.push_back(truefalse(crt));
                crt="";
            }
            else if(crt!=""&&!oper(crt))
            {
                rez.push_back(crt[0]-'A'+2);
                crt="";
            }
            else if(crt!=""&&oper(crt))
            {
                while(!S.empty() && OP[S.top()].first>=OP[crt].first&&OP[S.top()].second==1)
                {
                    rez.push_back(COD[S.top()]);
                    S.pop();
                }
                S.push(crt);
                crt="";
            }
            if(c=='(')
                S.push("(");
            else if(c==')')
            {
                while(!S.empty()&&S.top()!="(")
                {
                    rez.push_back(COD[S.top()]);
                    S.pop();
                }
                S.pop();
            }
        }
    }
    while(!S.empty())
    {
        rez.push_back(COD[S.top()]);
        S.pop();
    }
    return rez;
}
int eval(vector<int> a)
{
    stack<int> S;
    for(auto i:a)
        if(i>=0)
        {
            int val=i;
            if(i>=2)
                val=V[i-2];
            S.push(val);
        }
        else
            if(i==-1)
            {
                int val=S.top();
                S.pop();
                S.push(1-val);
            }
            else
            {
                int v1=S.top();
                S.pop();
                int v2=S.top();
                S.pop();
                if(i==-2)
                    S.push(v1&v2);
                else
                    S.push(v1|v2);
            }
    return S.top();
}
int main()
{
    getline(fi,input);
    fi>>n>>schimb;
    initOP();
    s=rpn(input);
    /*
    for(auto it:s)
        fo<<it<<" ";
        */
    for(auto it:schimb)
    {
        V[it-'A']=1-V[it-'A'];
        fo<<eval(s);
    }
    fi.close();
    fo.close();
    return 0;
}