Cod sursa(job #80247)

Utilizator MariusMarius Stroe Marius Data 27 august 2007 01:07:23
Problema Bool Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.08 kb
#include <fstream>
#include <string.h>

using namespace std;

const char iname[] = "bool.in";
const char oname[] = "bool.out";

#define MAXL  1024

int V[256];


int f(char O[], int cnt)
{
	int S[MAXL], cnts = 0;

	for (int i = 0; i < cnt; ++ i) {
		if (('A' <= O[i]) && (O[i] <= 'Z'))
			S[cnts ++] = V[O[i]];
		else if ((O[i] == '0') || (O[i] == '1'))
			S[cnts ++] = O[i] - '0';
		else if (O[i] == '!')
			S[cnts - 1] ^= 1;
		else if (O[i] == '&')
			S[cnts - 2] = S[cnts - 2] & S[cnts - 1], cnts --;
		else if (O[i] == '|')		
			S[cnts - 2] = S[cnts - 2] | S[cnts - 1], cnts --;
	}
	return S[0];
}

int main(void)
{
	char E[MAXL], S[MAXL], O[MAXL], ch;
	int n;

	int cnts, cnto, i, len;

	ifstream fin(iname);

	fin.getline(E, MAXL);
	len = int(strlen(E));

    for (cnts = cnto = i = 0; i < len; ++ i) {
		if (E[i] == ' ')
			continue ;
		else if (E[i] == '(')
			S[cnts ++] = '(';
		else if (E[i] == ')') {
			while (S[cnts - 1] != '(')
				O[cnto ++] = S[-- cnts];
			cnts --;
		} else if (E[i] == 'O') {
			if (strncmp(&E[i], "OR", 2) == 0) {
				while ((cnts > 0) && ((S[cnts - 1] == '&') || (S[cnts - 1] == '!')))
					O[cnto ++] = S[-- cnts];
				S[cnts ++] = '|', i += 1;
			} else
				O[cnto ++] = E[i];
		} else if (E[i] == 'A') {
			if (strncmp(&E[i], "AND", 3) == 0) {
				while ((cnts > 0) && (S[cnts - 1] == '!'))
					O[cnto ++] = S[-- cnts];
				S[cnts ++] = '&', i += 2;
			} else
				O[cnto ++] = E[i];
		} else if (E[i] == 'N') {
			if (strncmp(&E[i], "NOT", 3) == 0)
				S[cnts ++] = '!', i += 2;
			else
				O[cnto ++] = E[i];
		} else if (E[i] == 'T') {
			if (strncmp(&E[i], "TRUE", 4) == 0)
				O[cnto ++] = '1', i += 3;
			else
				O[cnto ++] = E[i];
		} else if (E[i] == 'F') {
			if (strncmp(&E[i], "FALSE", 5) == 0)
				O[cnto ++] = '0', i += 4;
			else
				O[cnto ++] = E[i];
		} else
			O[cnto ++] = E[i];
	}
	while (cnts > 0)
		O[cnto ++] = S[-- cnts];

	ofstream fout(oname);
	
	for (fin >> n; n > 0; -- n)
		fin >> ch, V[ch] ^= 1, fout << f(O, cnto);

	fin.close();
	fout.close();
	return 0;
}