#include #include static int __carriage_initialised = 0; /* 1 if initialised */ static int __carriage_nb_cells; /* number of cells */ static int __carriage_goal; /* index of the hidden box */ static int __carriage_open_cost; /* open cost */ static int __carriage_rev_cost; /* reverse cost */ static int __carriage_pos; /* current position */ static int __carriage_dir; /* current direction (-1 or 1) */ static long long int __carriage_cost; /* current total cost */ static void __carriage_msg(long long int score, const char *msg) { if (score < 0) printf("%s\n", msg); else printf("Found the prince using %lld coins!\n", score); exit(0); } static void __carriage_init(void) { if(__carriage_initialised != 0) return; __carriage_initialised = 1; if(scanf("%d%d%d%d", &__carriage_nb_cells, &__carriage_rev_cost, &__carriage_open_cost, &__carriage_goal) != 4) __carriage_msg(-1, "Invalid input, expecting 4 integers."); if (__carriage_goal < 0 || __carriage_goal >= __carriage_nb_cells) __carriage_msg(-1, "Invalid prince's castle position."); __carriage_pos = 0; __carriage_dir = 1; __carriage_cost = 0; } /* returns the number of cells */ int carriage_nb_cells() { __carriage_init(); return __carriage_nb_cells; } /* returns the cost of reversing the direction */ int carriage_reverse_cost() { __carriage_init(); return __carriage_rev_cost; } /* returns the cost of opening a box */ int carriage_open_cost() { __carriage_init(); return __carriage_open_cost; } /* moves the carriage (negative for left, positive for right) */ void carriage_move(int n) { __carriage_init(); if(n * __carriage_dir < 0) { __carriage_cost += (long long int)(__carriage_rev_cost); __carriage_dir *= -1; } __carriage_pos += n; if(__carriage_pos < 0 || __carriage_pos >= __carriage_nb_cells) __carriage_msg(-1, "Move outside valid cells"); } /* open the box on the current cell, returns -1 if the box you are * looking for is on the left, +1 if the box is on the right and * the function will exit if the box contains the number. */ int carriage_open() { __carriage_init(); __carriage_cost += (long long int)(__carriage_open_cost); if(__carriage_pos == __carriage_goal) __carriage_msg(__carriage_cost, ""); return __carriage_pos < __carriage_goal ? 1 : -1; }