The Crazy Eights Problem

Crazy Eights is a card game usually played by two or more people. We will use a solitare version here. In the game, cards are played on a discard pile. Which cards can be played on the pile depends on the card on top of the pile. It is legal to play any card of the same suit or the same denomination as the card on top of the discard pile. The new card played is now the top of the discard pile. Eights are wild, meaning they can be played on any card and any card may be played on an eight (in this sense the solitaire version is different since in the non-solitaire version a player specifies a suit when playing an eight.)

In our solitaire version, you will be given a hand of one or more cards, and the initial card on top of the discard pile and you will determine if you can discard all your cards. Your output for each hand will be a line containing YES or NO, accordingly.

The first line of input will contain a single positive integer n, indicating how many hands are to be played. There will be n lines following, each giving the top card of the discard pile, followed by one or more cards that make up a hand. Each card will be given by two adjacent characters giving first the denomination, then the suit. A single space will separate cards and the last valid card on a line will be followed by XX (which isn't a valid card.) There will be no more than 12 cards on a line, including the top of the discard pile card. We will use 1, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A for the denominations and S, H, D, C for the suits. Thus a line containing

     JS 4H 4C TH 5C JC

indicates that a Jack of Spades is on top of the discard pile and the hand consists of 5 cards, three of them clubs and the other two hearts. Notice that you can indeed discard all the cards in this hand.

Sample Input

6
JS 4H 4C TH 5C JC XX
7H AD JH 2H 9S TH 5D 6H 4C XX
AC 4C 5C KS 6C 6S TC 4D TD XX
QD KD 8S 4C 3C XX
AH 4D XX
AH 8S XX

Sample Output

YES
NO
YES
YES
NO
YES

Submit

submit149 crazy ...