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

Stacks of Flapjacks

120.c

/* Stacks of Flapjacks */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int len;
int stack[35];

int sorted[35];

int
compar(const void *a, const void *b) {
	int i = *(int *)a;
	int j = *(int *)b;

	return i-j;
}

void
flip(int num) {
	int i;
	int t;

	for(i=0; i<(len-num+1)/2; i++) {
		t = stack[i];
		stack[i] = stack[len-num-i];
		stack[len-num-i] = t;
	}
	printf("%d ", num);
}

void
doit(void) {
	int i,j;

	for(i=len-1; i>=0; i--) {
		if (stack[i]==sorted[i]) {
			continue;
		}
		if (stack[0]!=sorted[i]) {
			for(j=0; j<i; j++) {
				if (stack[j]==sorted[i]) {
					flip(len-j);
					break;
				}
			}
		}
		flip(len-i);
	}
	printf("0\n");
}

int main(void)
{
	char buf[1024];

	while(fgets(buf, 1024, stdin)) {
		char *s;

		printf("%s", buf);

		len=0;
		s = strtok(buf, " \t\r\n");
		while(s) {
			if (sscanf(s, "%d", &stack[len++])!=1) {
				abort();
			}
			s = strtok(NULL, " \t\r\n");
		}
		memcpy(sorted, stack, len*sizeof(int));
		qsort(sorted, len, sizeof(int), compar);
		doit();
	}
	exit(0);
}