Cod sursa(job #2209377)

Utilizator georgitTreista Georgiana georgit Data 3 iunie 2018 10:49:03
Problema Bool Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.88 kb
#include<fstream>
#include<stack>
#include<cstring>

using namespace std;
bool V[10000];
bool isdigit(char c)
{
    return (c=='0' or c=='1');
}
bool isoperator(char c)
{
    return (c=='&' or c=='|');
}
bool isletter(char c)
{
	return (c>='A' and c<='Z');
}
int getpriority(char op)
{
    if(op=='&') return 2;
    if(op=='!') return 3;
    if(op=='|') return 1;
	return 0;
}
int higherpriority(char op1, char op2)
{
	return (getpriority(op1)>=getpriority(op2));
}
string reversepolishnotation(char exp[])
{
	stack<char> S;
	string postfix;
	for(int i = 0;i< strlen(exp);i++)
    {
        bool ok=1;
        if(isletter(exp[i]) and isletter(exp[i+1]))
        {
            ok=0;
            bool k=0;
            int pas=0;
            char op;
            if(exp[i]=='T') {postfix+='1';pas=3;k=1;}
            if(exp[i]=='F') {postfix+='0';pas=4;k=1;}
            if(exp[i]=='A') {op='&';pas=2;}
            if(exp[i]=='O') {op='|';pas=1;}
            if(exp[i]=='N') {S.push('!');pas=2;}
            else if(k==0)
            {
                while(!S.empty() and S.top()!='(' and higherpriority(S.top(),exp[i]))
                {
                    postfix+= S.top();
                    S.pop();
                }
                S.push(op);
            }
            i+=pas;
        }
        if(isletter(exp[i]) and ok)
        {
            ok=0;
            postfix+=exp[i];
        }
        if (exp[i] == '(' and ok)
        {
            ok=0;
            S.push(exp[i]);
        }

        if(exp[i] == ')' and ok)
        {
            ok=0;
            while(!S.empty() and S.top()!='(')
            {
                postfix += S.top();
                S.pop();
            }
            S.pop();
        }
    }
	while(!S.empty())
    {
		postfix += S.top();
		S.pop();
	}
	return postfix;
}
int val(int op1, int op2, char c)
{
    if(c=='|') return op1|op2;
    if(c=='&') return op1&op2;
}
int value(string postfix)
{
    int answer=0;
    stack <bool> S;
    for(int i=0;i<postfix.size();i++)
    {
        if(isletter(postfix[i]) or isdigit(postfix[i]))
        {
            S.push(V[postfix[i]]);
        }
        if(postfix[i]=='!')
        {
            int nr=S.top();
            S.pop();
            S.push(1-nr);
        }
        else
        if(isoperator(postfix[i]))
        {
            int op1=S.top();
            S.pop();
            int op2=S.top();
            S.pop();
            S.push(val(op2,op1,postfix[i]));
        }
    }
    return S.top();
}
int main()
{
    ifstream f("bool.in");
    ofstream g("bool.out");
	char exp[1000];
	f.get(exp,1000);
	int n;
	f>>n;
	string postfix=reversepolishnotation(exp);
	V['1']=1;
	V['0']=0;
    for(int i=1;i<=n;i++)
    {
        char c;
        f>>c;
        V[c]=1-V[c];
        g<<value(postfix);
    }
	return 0;
}