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

Roman Roulette

130.c

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

int n,k;
int pe[120];

int
recorre(int start) {
	int i;
	int c = k;

	while (1) {
		for (i=start; i<n; i++) {
			if (pe[i]>0) {
				c--;
				if (!c) {
					return i;
				}
			}
		}
		start=0;
	}
}

int
calc(int start) {
	int i;
	int a,b;
#if DEBUG
	for (i=0; i<n; i++) {
		printf(" %d", pe[i]);
	}
	printf("\n");
	printf("calc(%d)\n", start);
#endif
	a=-1;
	for (i=0; i<n; i++) {
		if (pe[i]<0) {
			continue;
		} else {
			if (a<0) {
				a=pe[i];
			} else {
				a=-1;
				break;
			}
		}
	}
	if (a>0) {
		return a;
	}
	a = recorre(start);
#if DEBUG
	printf("muere %d, ", pe[a]);
#endif
	pe[a] = -1;
	b = recorre(a);
#if DEBUG
	printf("se mueve %d\n", pe[b]);
#endif
	pe[a] = pe[b];
	pe[b] = -1;

	return calc(a+1);
}

int
main(void) {
	int i;

	while (1) {
		scanf("%d %d", &n, &k);
		if (n==0 && k==0) {
			return 0;
		}
		for (i=0; i<n; i++) {
			pe[i] = i+1;
		}
		i = calc(0);
		i = (n+2-i) % n;
		if (i==0) i=n;
		printf("%d\n", i);
	}
}