Bob's Rummikub
Time limit2.5sMemory limit512 MB
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.
- Rummikub is played with tiles numbered 1 through 7 in four colors (blue, red, yellow, black), for a total of 28 tiles.
- Exactly one tile exists for each combination of a number and a color.
- When Bob plays tiles, the tiles on the table must form Rummikub sets.
- 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.
- The tiles on the table form Rummikub sets when the tiles can be split into groups such that every group is a Rummikub set.
- 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.