This page is still under construction.

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

Bob's Rummikub

Time limit2.5sMemory limit512 MB

Summary
Given tiles in hand and a legal table arrangement, find the largest number of hand tiles Bob can add while keeping the whole table partitionable into groups and runs.
Level

Medium7 of 10

Topics
Backtracking, Brute force, Implementation, Combinatorics
Solved
No attempts yet

Problem

Bob enjoys playing Rummikub. Given all of the tiles in Bob's hand and all of the tiles already on the table, output the maximum number of tiles Bob can play.

The rules of Rummikub are as follows.

  1. Rummikub is played with tiles numbered 1 through 7 in four colors (blue, red, yellow, black), for a total of 28 tiles.
  2. Exactly one tile exists for each combination of a number and a color.
  3. When Bob plays tiles, the tiles on the table must form Rummikub sets.
  4. Rummikub sets come in two kinds: groups and runs. A group is 3 or 4 tiles with different colors and the same number, and a run is 3 or more tiles with the same color and consecutive numbers.
  5. The tiles on the table form Rummikub sets when the tiles can be split into groups such that every group is a Rummikub set.
  6. When Bob plays tiles, he may use the tiles on the table to form Rummikub sets. The tiles on the table must still form Rummikub sets.

Input

The first line gives the number of tiles in Bob's hand, n. (1 ≤ n ≤ 28)

The second line gives information about the tiles in Bob's hand, separated by spaces.

The third line gives the number of tiles on the table, m. (0 ≤ m ≤ 28-n)

The fourth line gives information about the tiles on the table, separated by spaces.

Information about a tile is given as a color (char) followed by a number (int). See the sample input and output.

The tiles on the table are guaranteed to form Rummikub sets, and the same tile is never given more than once.

Output

Output the maximum number of tiles Bob can play.

Examples2

  1. Example 1

    Input
    3
    blue3 blue5 blue6
    4
    blue4 yellow4 red4 black4
    
    Expected output
    3
    
  2. Example 2

    Input
    8
    blue6 blue7 yellow3 yellow6 red3 red6 red7 black1 
    9
    blue2 blue4 yellow2 yellow4 red2 red4 black2 black3 black4 
    
    Expected output
    5