#include int main(int argc, char *argv[]) { /* The Elves play this game by taking turns arranging the marbles in * a circle according to very particular rules. */ #define MAX_ELVES 1000 static long score[MAX_ELVES] = {0}; long winning_score; int elf, num_elves; #define MAX_MARBLES 10000000 static int circle[MAX_MARBLES]; int current, gap; int marble, last; if ( argc < 3 || sscanf(argv[1], "%d", &num_elves) != 1 || num_elves > MAX_ELVES || sscanf(argv[2], "%d", &last) != 1 || last >= MAX_MARBLES ) return 1; /* The marbles are numbered starting with 0 and increasing by 1 * until every marble has a number. */ marble = 0; /* First, the marble numbered 0 is placed in the circle. * At this point, while it contains only a single marble, it is * still a circle: the marble is both clockwise from itself and * counter-clockwise from itself. This marble is designated the * current marble. */ circle[0] = marble++; current = 0; gap = 1; /* Then, each Elf takes a turn... */ for (;;) for (elf = 0; elf < num_elves; elf++) { if (0) { printf("%d: @%d ", elf, current); for (int i = current; i != gap;) { printf("%d ", circle[i++]); if (i == MAX_MARBLES) i = 0; } putchar('\n'); } /* ...placing the lowest-numbered remaining marble * into the circle between the marbles that are 1 and * 2 marbles clockwise of the current marble. (When * the circle is large enough, this means that there * is one marble between the marble that was just * placed and the current marble.) The marble that * was just placed then becomes the current marble. * * However, if the marble that is about to be placed * has a number which is a multiple of 23, something * entirely different happens. */ if (marble % 23) { circle[gap++] = circle[current++]; if (gap == MAX_MARBLES) gap = 0; if (current == MAX_MARBLES) current = 0; circle[gap++] = circle[current]; if (gap == MAX_MARBLES) gap = 0; circle[current] = marble++; } else { /* First, the current player keeps the marble * they would have placed, adding it to their * score. */ score[elf] += marble++; /* In addition, the marble 7 marbles counter- * clockwise from the current marble is removed * from the circle and also added to the * current player's score. The marble located * immediately clockwise of the marble that was * removed becomes the new current marble. */ for (int i = 0; i < 6; i++) { if (current == 0) current = MAX_MARBLES; if (gap == 0) gap == MAX_MARBLES; circle[--current] = circle[--gap]; } if (gap == 0) gap == MAX_MARBLES; score[elf] += circle[--gap]; } /* The goal is to be the player with the highest score */ /* after the last marble is used up. */ if (marble > last) goto game_over; } game_over: winning_score = 0; for (elf = 0; elf < num_elves; elf++) { if (score[elf] > winning_score) { winning_score = score[elf]; } } printf("%ld\n", winning_score); return 0; }