Cod sursa(job #2701666)

Utilizator VasAlexVasiluta Alex VasAlex Data 1 februarie 2021 00:23:57
Problema Bool Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.55 kb
#include <bits/stdc++.h>
using namespace std;
#ifndef offline
string nume_problema = "bool";
ifstream fin(nume_problema + ".in");
ofstream fout(nume_problema + ".out");
#define cin fin
#define cout fout
#endif
enum operand
{
	FALSE = 0b000000,
	TRUE = 0b000001,
	AND = 0b000010,
	OR = 0b000100,
	NOT = 0b001000,
	LETTER = 0b010000,
	EXPRESSION = 0b100000
};

struct expr
{
	vector<operand> ops;
	vector<operand> tmp1, tmp2;
	expr() {}
	void gradnot()
	{
		for (int i = 0; i < ops.size(); i++)
		{
			if (ops[i] == NOT)
				tmp1.push_back(ops[++i] == TRUE ? FALSE : TRUE);
			else
				tmp1.push_back(ops[i]);
		}
	}
	void gradand()
	{
		for (int i = 0; i < tmp1.size() - 1; i += 2)
		{
			if (tmp1[i + 1] == AND)
				tmp1[i + 2] = (tmp1[i] & tmp1[i + 2]) == TRUE ? TRUE : FALSE;
			else
			{
				tmp2.push_back(tmp1[i]);
				tmp2.push_back(tmp1[i + 1]);
			}
		}
		tmp2.push_back(tmp1.back());
	}
	operand grador()
	{
		for (int i = 0; i < tmp2.size(); i += 2)
			if (tmp2[i] == TRUE)
				return TRUE;
		return FALSE;
	}
	operand execute()
	{
		gradnot();
		gradand();
		dbg();
		operand rez = grador();
		// cerr << rez << endl;
		return rez;
	}
	void dbg()
	{
		return;
		cerr << "ops: ";
		for (const auto &i : ops)
			cerr << i << " ";
		cerr << endl;
		cerr << "tmp1: ";
		for (const auto &i : tmp1)
			cerr << i << " ";
		cerr << endl;
		cerr << "tmp2: ";
		for (const auto &i : tmp2)
			cerr << i << " ";
		cerr << "\n\n";
	}
};
stack<expr> st;
bool vars[128];

void addOperand(vector<operand> &v, const string &val)
{
	if (val == "")
		return;
	if (val.size() == 1)
	{
		v.push_back(vars[val[0]] == 1 ? TRUE : FALSE);
		return;
	}
	if (val == "TRUE")
		v.push_back(TRUE);
	else if (val == "FALSE")
		v.push_back(FALSE);
	else if (val == "AND")
		v.push_back(AND);
	else if (val == "NOT")
		v.push_back(NOT);
	else if (val == "OR")
		v.push_back(OR);
	else
		cerr << "S-a stricat ceva: \"" << val << "\"\n";
}

void execute(const string &s)
{
	expr blank;
	st.push(blank);
	string val;
	istringstream strin(s);
	char c;
	while (strin >> c)
	{
		if (c == '(')
		{
			expr blank;
			st.push(blank);
		}
		else if (c == ')')
		{
			operand op = st.top().execute();
			st.pop();
			st.top().ops.push_back(op);
			val = "";
		}
		else
		{
			val += c;
			if (!isalpha(strin.peek())) // adăugăm operanzii
			{
				addOperand(st.top().ops, val);
				val = "";
			}
		}
	}

	addOperand(st.top().ops, val);
	cout << st.top().execute();
	st.pop();
}

int main()
{
	string ops;
	getline(cin, ops);
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		char a;
		cin >> a;
		vars[a] ^= 1;
		execute(ops);
	}
	return 0;
}