Photolog

Through the Looking-Glass
2010-10-12: Through the Looking-Glass
My radio speaks is binary!
2010-10-10: My radio speaks is binary!
Gigaminx: (present for my birthday)
2010-09-16: Gigaminx: (present for my birthday)
Trini on bike
2010-09-05: Trini on bike
Valporquero
2010-08-28: Valporquero
My new bike!
2010-08-22: My new bike!
Mario and Ana's wedding
2010-08-13: Mario and Ana's wedding
Canyoning in Guara
2010-08-07: Canyoning in Guara
Trini and Mari in Marbella
2010-08-05: Trini and Mari in Marbella
Trini and Chelo in Tabarca
2010-08-03: Trini and Chelo in Tabarca
Valid XHTML 1.1
Log in
Back to list of problems

The Blocks Problem

101.c

#include <stdio.h>
#include <string.h>

int n;
int blocks[30][30];

void
find(int i, int*a, int*b) {
	int p,q;

	for(p=0; p<n; p++) {
		for(q=1; q<=blocks[p][0]; q++) {
			if (blocks[p][q]==i) {
				*a = p;
				*b = q;
				return;
			}
		}
	}
	abort();
}

void
back(int a, int b) {
	int i;

	for(i=b; i<=blocks[a][0]; i++) {
		blocks[blocks[a][i]][0] = 1;
		blocks[blocks[a][i]][1] = blocks[a][i];
	}
	blocks[a][0] = b-1;
}


void
printit(void) {
	int i,j;

	for(i=0; i<n; i++) {
		printf("%d:", i);
		for(j=1; j<=blocks[i][0]; j++) {
			printf(" %d", blocks[i][j]);
		}
		printf("\n");
	}
}

int
main(void) {
	int i,j;
	char buf[1024];
	int a,b,c,d;
	int p;

	fgets(buf, 1024, stdin);
	sscanf(buf, "%d", &n);

	for(i=0; i<n; i++) {
		blocks[i][0] = 1;
		blocks[i][1] = i;
	}

	while(1) {
		char word1[10];
		char word2[10];

		fgets(buf, 1024, stdin);
		sscanf(buf, "%s %d %s %d", word1, &i, word2, &j);
		if (!strcmp(word1, "quit")) {
			break;
		}
		find(i, &a, &b);
		find(j, &c, &d);
		if (a==c || i==j) {
			continue;
		}

		if (!strcmp(word1, "move")) {
			back(a, b+1);
		}
		if (!strcmp(word2, "onto")) {
			back(c, d+1);
		}

		d = blocks[c][0];
		for(p=0; b<=blocks[a][0]; p++) {
			blocks[c][++d] = blocks[a][b++];
		}
		blocks[a][0] -= p;
		blocks[c][0] = d;

	}
	printit();
	return 0;
}