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; }