Cod sursa(job #481138)

Utilizator Programmer01Mierla Laurentiu Marian Programmer01 Data 30 august 2010 18:54:39
Problema Bool Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.53 kb
#include<stdio.h>
#include<string.h>

char *s, *p, *tokens, operators[2] = {'|', '&'};
int values[150];

char shortForm(char *str){
	if(!strncmp(str, "AND", 3)) return '&';
	if(!strncmp(str, "OR", 2)) return '|';
	if(!strncmp(str, "NOT", 3)) return '!';
	if(!strncmp(str, "TRUE", 4)) return '1';
	if(!strncmp(str, "FALSE", 5)) return '0';
	return str[0];
}

void tokenize(){
	char str[6], *i = tokens;
	for(p = s; *p; ++p) {
		int j = 0;
		for(; *p && *p != '(' && *p != ')' && *p != ' '; ++p, ++j)
			str[j] = *p;
		if(j > 0) {
			str[j] = '\0';
			*i++ = shortForm(str);
		}
		if(*p == '(' || *p == ')')
			*i++ = *p;
	}
	
	*i = '\0';
}

int compute(char op, int x, int y){
	if(op == '&') return x & y;
	return x | y;
}

int eval(int level){
	int x, y;
	if(level == 2){
		if(*p == '!') {
			++p;
			x = !eval(level);
		}
		else if(*p == '(') {
			++p;
			x = eval(0);
			++p;
		}
		else x = values[*p++];
	}
	else for(x = eval(level+1); operators[level] == *p; x = y){
		char op = *p++;
		y = compute(op, x, eval(level+1));
	}
	
	return x;
}

int main()
{
	FILE *ifile, *ofile;
	int n;
	char c;
	
	s = new char[1001];
	ifile = fopen("bool.in", "r");
	fgets(s, 1000, ifile);
	
	tokens = new char[strlen(s)+1];
	tokenize();
	values['1'] = 1;
	
	ofile = fopen("bool.out", "w");
	
	fscanf(ifile, "%i\n", &n);
	for(int i=0; i<n; i++) {
		fscanf(ifile, "%c", &c);
		values[c] = !values[c];
		p = tokens;
		fprintf(ofile, "%i", eval(0));
	}
	
	fclose(ifile);
	fclose(ofile);	
	return 0;
}