Shuffling Patience

No attempts yetTime limit1sMemory limit128 MB

Problem

Many children enjoy playing cards, especially the simpler forms of patience (solitaire), yet many find it hard to shuffle the cards well. The following "patience" game helps with this while also aiding card recognition and simple arithmetic. The essence is to "cover" exposed pairs or triples of cards that stand in a specific relationship to one another.

A deck has 52 cards, in four suits of 13 ranks each. The suits are spades (S), hearts (H), clubs (C), and diamonds (D); the ranks are ace (A, face value 1), 2, 3, 4, 5, 6, 7, 8, 9, 10 (T), jack (J), queen (Q), and king (K).

During play, up to 16 piles may be created in a 4-by-4 grid if needed (usually fewer are required). Deal the cards face up into this 4x4 grid. Before playing each card, check whether a pair or triple of the cards already played can be covered.

  • A pair of cards can be covered if both are ranked ace to ten and their face values add up to 11.
  • A triple of cards can be covered if they form the set {jack, queen, king}.

If no such pair or triple exists, a new pile is started.

When more than one pair and/or triple exists, only one is covered before the situation is reassessed. Cards are always covered in the order they were dealt, that is, left to right, top to bottom. The first card covered is the eligible card nearest the start of play. The second card covered (and the third, for a triple) is its partner nearest the start of play. For example, if the first part of a deck is TS QC 8S 8D QH 2D 3H KH 9H..., the first seven cards are played as follows:

TS  QC  8S  8D
QH  2D  3H

The next two cards (KH and 9H) then cover the pair 8S and 3H respectively. Covering a pair or triple is treated as a single, indivisible operation, so no further covering is considered until it is complete.

Write a program to simulate this game. Read in one or more decks of cards, simulate the play, and determine how many cards are on each pile at the end. If it is not possible to stay within the 16 allowed piles, terminate that deal with the message described below.

Input

The input consists of a series of decks of cards, each deck given as 4 lines of 13 cards. Each card is written as two characters: a rank (A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K) followed by a suit (S, H, C, D). The cards are listed in the order they will be played. The input is terminated by a line containing a single #.

Output

The output consists of one line per deck. Each line begins with the deck number followed by a colon.

  • If a deck cannot be played within the 4x4 grid, write a single space followed by the message Overflowed on card no and the number of the card about to be dealt.
  • If the whole deck can be played, write the (non-zero) numbers of cards on each pile, from the leftmost pile onward, once the deck has been fully dealt.

The deck number and every pile count are right-justified in a field 3 characters wide.