Найдите победителя в игре N шаров, в которой игрок может удалить любые шары в диапазоне [A, B] за один ход.

Опубликовано: 19 Сентября, 2022

Имея два целых числа A и B , а также учитывая, что Алиса и Боб играют в игру, начинающуюся с мешка, содержащего N шаров, в которой за один ход игрок может удалить любое количество шаров из диапазона [A, B] и если игрок не может убрать ни одного шара, то игрок проигрывает, задача состоит в том, чтобы найти победителя игры, если Алиса и Боб ведут игру альтернативно и оптимально, а Алиса начинает игру.

Примеры:

Input: N = 2, A = 1, B = 1
Output: Bob
Explanation: 
One way in which the game can be played is:

  1. Alice removes 1 ball, so the remaining balls are 1.
  2. Now, Bob removes the last ball.
  3. Alice cannot remove any balls, so she loses.

Input: N = 3, A = 1, B = 2
Output: Bob

Наивный подход. Самый простой подход — найти число Гранди для каждого состояния и найти выигрышное и проигрышное состояния с помощью теоремы Спрага — Гранди.

Временная сложность: O(N*N!)
Вспомогательное пространство: O(N)

Эффективный подход. Описанный выше подход можно оптимизировать на основе следующих наблюдений:

  1. Firstly, it can be observed that (A + B) is always losing state, because whatever X (A ≤ X ≤ B) number of balls the current player chooses, the opponent can always empty the bag as there will be (A + B – X) number of balls left where A ≤ (A + B – X) ≤ B.
  2. Also, from previous observations, one can observe that, for any multiple of (A + B) say, m*(A + B), the opponent can always reduce the current player to a state of (m – 1)*(A + B) and from (m – 1)*(A + B) to (m – 2)*(A + B) and so on.
  3. Thus, extending the above observation, one can say that for any multiple of (A + B), the opponent can always reduce the current player to a state of exactly (A + B), which is indeed a losing state. Therefore, all multiples of (A + B) are a losing state.
  4. So, the optimal choice for any player is to reduce the opponent to a multiple of (A + B), because after this, the player can always win, no matter what the opponent’s moves are.
  5. So, now losing states are the states from which one can never reduce the opponent to a multiple of (A + B).
  6. Therefore, any player with the state of the form: ((A + B)*m + y), where (0 ≤  y ≤ A-1) can never force the opponent to reduce to a multiple of (A + B), as any player can only pick at least A and at most B number of balls.

Выполните следующие шаги, чтобы решить проблему:

  • Если N%(A+B) меньше A, то выведите « Bob ».
  • В противном случае выведите « Алиса ».

Ниже приведена реализация вышеуказанного подхода:

Временная сложность: O(1)
Вспомогательное пространство: O(1)