#P10968. Distinct Adjacent Face Arrangement

    ID: 13017 Type: Default 1000ms 256MiB

Distinct Adjacent Face Arrangement

Distinct Adjacent Face Arrangement

A standard deck without jokers consists of 52 cards. It is divided into 4 suits: spades (S), hearts (H), diamonds (D) and clubs (C); each suit contains 13 cards of distinct face values. Each card is represented as a two‐character string: the first character denotes the face value (one of 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A) and the second character denotes the suit (S, H, D, C). Given a set of cards (all cards are distinct), arrange them in a row such that any two adjacent cards have different face values, and compute the number of valid arrangements.

Note: The face value of a card is determined by its first character. For example, both 2S and 2H have the face value 2, so they cannot be adjacent in a valid arrangement.

The answer can be expressed recursively. Let \(f(c_0,c_1,\ldots,c_{12}, \ell)\) be the number of valid orders when the remaining count for face \(i\) is \(c_i\) for face corresponding to the order in \(2,3,4,5,6,7,8,9,T,J,Q,K,A\) and \(\ell\) is the index of the face chosen last (or a special value if no card has been chosen yet). Then:

[ f(c_0,\ldots,c_{12},\ell)=\sum_{i=0}^{12}!\Bigl[\mathbb{1}{{c_i>0}},\mathbb{1}{{i\neq \ell}},f(c_0,\ldots,c_i-1,\ldots,c_{12}, i)\Bigr] ]

with the base case \(f(0,0,\ldots,0,\ell)=1\).

inputFormat

The input consists of cards. It can be given in one of the following two formats:

  • The first token is an integer \(n\) (\(1\le n\le52\)), followed by \(n\) card representations separated by spaces on the same or subsequent lines.
  • If no integer is provided, the entire line (or all tokens) are treated as card representations.

outputFormat

Output a single integer, the number of valid arrangements where adjacent cards have distinct face values.

sample

3
2S 3H 4D
6