Cod sursa(job #4527)

Utilizator plastikDan George Filimon plastik Data 5 ianuarie 2007 11:55:48
Problema Perle Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.79 kb
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <string.h>

int N;
struct pearl {
	char type;
	pearl *next;
};
pearl *des, *ava;

void add(pearl *&start, char ptype) {
	if (start == NULL) {
		start = new pearl;
		start->type = ptype;
		start->next = NULL;
		return;
	}
	pearl *ipearl;
	for (ipearl = start; ipearl->next != NULL; ipearl = ipearl->next);
	ipearl->next = new pearl;
	ipearl->next->type = ptype;
	ipearl->next->next = NULL;
}
void add_r(pearl *&start, char ptype) {
	if (start == NULL) {
		start = new pearl;
		start->type = ptype;
		start->next = NULL;
		return;
	}
	pearl *npearl = new pearl;
	npearl->type = ptype;
	npearl->next = start;
	start = npearl;
}
void add(pearl *&start, char *stype) {
	int i;
	for (i = strlen(stype)-1; i >= 0; i--)
		add_r(start, stype[i]);
}

char pop(pearl *&start) {
	char type = start->type;
	pearl *x = start;
	start = start->next;
	delete x;
	return type;
}
void clean(pearl *&des) {
	while ((des != NULL) && (ava != NULL) && (des->type == ava->type)) {
		pop(des);
		pop(ava);		
	}
}
int test(char ptype) {
	pearl *des_a = des;
	ava = NULL;
	add(ava, ptype);
	/*clean();*/
	while ((ava != NULL) && (des_a != NULL) && (ava->type != des_a->type)) {
		char at, dt;
		at = ava->type;
		dt = des_a->type;
		pop(ava);
		switch(dt) {
			case '1': {
				switch(at) {
					case 'A': {add(ava, "1"); break;}
					case 'B': {add(ava, "1A3AC"); break;}
					case 'C': {add(ava, "12A"); break;}
					default: return 0;
				}
				break;
			}
			case '2': {
				switch (at) {
					case 'A': {add(ava, "2"); break;}
					case 'B': {add(ava, "2B"); break;}
					case 'C': {add(ava, "2"); break;}
					default: return 0;
				}
				break;
			}
			case '3': {
				switch(at) {
					case 'A': {add(ava, "3"); break;}
					case 'B': return 0;
					case 'C': {add(ava, "3BC"); break;}
					default: return 0;
				}
				break;
			}
		}
		clean(des_a);
	}
	if ((ava == NULL && des_a != NULL) || (ava != NULL && des_a == NULL))
		return 0;
	return 1;
}
int main(void) {
	FILE *in = fopen("perle.in", "r"),
		 *out = fopen("perle.out", "w");

	fscanf(in, "%d", &N);
	int i;
	for (i = 1; i <= N; i++) {
		des = NULL;
		int li, j;
		fscanf(in, "%d", &li);
		for (j = 1; j <= li; j++) {
			int ptype;
			fscanf(in, "%d", &ptype);
			add(des, (char)ptype+'0');
		}
		int ok = 0;
		ok = test('A');
		if (ok) {
			fprintf(out, "1\n");
			continue;
		}
		ok = test('B');
		if (ok) {
			fprintf(out, "1\n");
			continue;
		}
		ok = test('C');
		if (ok) {
			fprintf(out, "1\n");
			continue;
		}
		fprintf(out, "0\n");
		/* TEST!
		pearl *ipearl = des;
		for (; ipearl != NULL; ipearl = ipearl->next)
			fprintf(out, "%c ", ipearl->type);*/

	}
	fclose(in);
	fclose(out);
	return 0;
}