This page is still under construction.

Parts of this page are still being built. What you see may change.

The Game of 31

Time limit1sMemory limit128 MB

Summary
Given a partly played game of 31 with four cards of each value 1 to 6, determine the winner under perfect play.
Level

Hard8 of 10

Topics
Game theory, Dynamic programming, Backtracking, Combinatorics
Solved
No attempts yet

Problem

The game of 31 was a favourite of con artists who rode the railroads in days of yore. The game is played with a deck of 2424 cards: four of each of 1, 2, 3, 4, 5, 6 (four cards labelled 1, four labelled 2, and so on). Initially all of the cards lie face up on the table and the discard pile is empty. The players then take turns. On each turn the current player picks up one unused card from the table and lays it on the discard pile. The goal is to be the last player to lay a card without letting the sum of the pile exceed 3131. Your task is to determine the eventual winner of a partially played game, assuming both players play the remainder of the game with a perfect strategy.

For example, in the following game player BB wins:

  1. Player AA plays 3.
  2. Player BB plays 5.
  3. Player AA plays 6.
  4. Player BB plays 6.
  5. Player AA plays 5.
  6. Player BB plays 6.

After player BB's final 6 the pile totals exactly 3131, so player AA can no longer move and player BB is the winner.

Input

The first line contains the number of test cases. Each of the following lines describes one test case: a sequence of zero or more digits representing a partially completed game. The first digit is player AA's move, the second is player BB's move, and so on, with the two players alternating. Finish each game using a perfect strategy for both players to determine who wins.

Output

For each game, print A or B on its own line to indicate the eventual winner.

Examples1

  1. Example 1

    Input
    5
    356656
    35665
    3566
    111126666
    552525
    
    Expected output
    B
    B
    A
    A
    A