Shuffle Game
InterviewTime limit1.5sMemory limit1024 MB
Given deck X and two decks P1 and P2, find the maximum LCS length between X and any interleaving of P1 and P2.
- Level
Medium6 of 10
- Topics
- Dynamic programming, String
- Solved
- No attempts yet
Problem
Shuffle Game is a simple card game between the dealer and the player. At the start, the same deck of cards is given to both the dealer and the player. Each card has a suit, one of C, D, H, or S, followed by a kind, one of 2, 3, 4, 5, 6, 7, 8, 9, 10, A, J, K, or Q. So there are 52 different cards, and the same card can appear more than once in a deck.
After the cards are dealt, the dealer builds their own deck from the dealt cards using any shuffling method and shows to the player. Then the player builds a deck as follows. starts empty.
- Step 1. Build two decks and from the deck the player was given. The two decks can have different sizes.
- Step 2. Interleave and . That is, repeatedly move the bottom card of or the bottom card of onto the current top of , until both and are empty. The player does not have to alternate between and . Both the dealer and the player build their decks from the same cards, so always contains the same cards as .
A deck is written as its sequence of cards from bottom to top. The player's score is the length of the longest common subsequence (LCS) of the sequences and .
For example, suppose the deck (C2, CJ, D5, HA, S7) with is given to both players. The dealer builds (CJ, D5, HA, C2, S7) and shows it to the player. The player builds (D5, HA) and (CJ, S7, C2), then interleaves them into (D5, CJ, S7, HA, C2). The score is 3, because (CJ, HA, C2) is a longest common subsequence of and . However, the player can interleave the same and into (CJ, D5, HA, S7, C2), which gives a score of 4.
Given , , , and , compute the maximum score the player can achieve after Step 2.
Input
The first line contains three positive integers , , and (, ), where is the number of cards in the initial deck, and and are the numbers of cards in and . The next three lines contain the dealer's deck with cards, and the player's decks with cards and with cards. Each card is written as its suit (an uppercase letter C, D, H, or S) followed by its kind (2, 3, 4, 5, 6, 7, 8, 9, 10, or the uppercase letter A, J, K, or Q). The cards on each line are listed from the bottom to the top of the corresponding deck.
Output
Print one line containing the maximum score the player can achieve from , , and after Step 2.