It's Raining, Man
InterviewTime limit2sMemory limit512 MB
Given a set of distinct cards, decide whether they can be ordered in a row so that each neighbouring pair shares a rank or a suit.
Problem
Walter is spending the holidays on his great-grandfather's farm. It has been raining for days. Sitting in the attic of an aged barn and digging through piles of dusty junk, Walter finds a bunch of old poker cards. The cards look antique and interesting, so he starts to lay them down one by one, side by side, on the floor. Then he notices that there is some order in the sequence: many pairs of neighbouring cards are either of the same rank or of the same suit.
"This might be a nice little puzzle," Walter says to himself. "Can I rearrange the cards so that every two neighbouring cards share the rank or the suit? But the bunch is incomplete, and that might cut down the possible arrangements badly."
You are given the cards Walter found. Decide whether all of them can be laid out in one row so that every two neighbouring cards have the same rank or the same suit.
Input
The input holds several test cases. Each test case is a single line that lists every card in the bunch. The line starts with the number of cards , followed by card descriptions separated by single spaces.
A card is written with two characters. The first character is the rank, where A is the ace, 2 to 9 are those numbers, X is 10, J is the jack, Q is the queen and K is the king. The second character is the suit, where C is clubs, D is diamonds, H is hearts and S is spades.
All cards inside one test case are different. The input holds at most 100 test cases and ends at the end of the file.
Output
For each test case print one line: YES if the cards can be laid out as required, NO otherwise.