Card Game (Codeforces 1932D)
Tags: Greedy, implementation

Two players are playing an online card game. The game is played using a 32-card deck. Each card has a suit and a rank. There are four suits: clubs, diamonds, hearts, and spades. We will encode them with characters 'C', 'D', 'H', and 'S', respectively. And there are 8 ranks, in increasing order: '2', '3', '4', '5', '6', '7', '8', '9'.Each card is denoted by two letters: its rank and its suit. For example, the 8 of Hearts is denoted as 8H.At the beginning of the game, one suit is chosen as the trump suit.In each round, players make moves like this: the first player places one of his cards on the table, and the second player must beat this card with one of their cards. After that, both cards are moved to the discard pile.A card can beat another card if both cards have the same suit and the first card has a higher rank than the second. For example, 8S can beat 4S. Additionally, a trump card can beat any non-trump card, regardless of the rank of the cards, for example, if the trump suit is clubs ('C'), then 3C can beat 9D. Note that trump cards can be beaten only by the trump cards of higher rank.There were $$$n$$$ rounds played in the game, so the discard pile now contains $$$2n$$$ cards. You want to reconstruct the rounds played in the game, but the cards in the discard pile are shuffled. Find any possible sequence of $$$n$$$ rounds that might have been played in the game.

Input: The first line contains integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow.The first line of a test case contains the integer number $$$n$$$ ($$$1\le n\le 16$$$).The second line of a test case contains one character, the trump suit. It is one of "CDHS".The third line of a test case contains the description of $$$2n$$$ cards. Each card is described by a two-character string, the first character is the rank of the card, which is one of "23456789", and the second one is the suit of the card, which is one of "CDHS". All cards are different.

Output: For each test case print the answer to it: Print $$$n$$$ lines. In each line, print the description of two cards, in the same format as in the input: the first card that was played by the first player, and then the card that was used by the second player to beat it. If there is no solution, print a single line "IMPOSSIBLE".If there are multiple solutions, print any of them.


Sample Inputs:
8
3
S
3C 9S 4C 6D 3S 7S
2
C
3S 5D 9S 6H
1
H
6C 5D
1
S
7S 3S
1
H
9S 9H
1
S
9S 9H
1
C
9D 8H
2
C
9C 9S 6H 8C

Sample Outputs:
3C 4C
6D 9S
3S 7S
IMPOSSIBLE
IMPOSSIBLE
3S 7S
9S 9H
9H 9S
IMPOSSIBLE
6H 9C
9S 8C

Solution (Python):
t = int(input())
for _ in range(t):
    n = int(input())
    trump = input()
    arr = input().split(' ')
    (s_type, c_type, d_type, h_type) = ([], [], [], [])
    for card in arr:
        if card[1] == 'C':
            c_type.append(card)
        elif card[1] == 'D':
            d_type.append(card)
        elif card[1] == 'H':
            h_type.append(card)
        else:
            s_type.append(card)
    (s_type, c_type, d_type, h_type) = (sorted(s_type), sorted(c_type), sorted(d_type), sorted(h_type))
    if trump == 'S':
        tmp = s_type
        s_type = c_type
        c_type = tmp
        trump = 'C'
    elif trump == 'H':
        tmp = h_type
        h_type = c_type
        c_type = tmp
        trump = 'C'
    elif trump == 'D':
        tmp = d_type
        d_type = c_type
        c_type = tmp
        trump = 'C'
    if trump == 'C':
        if len(d_type) % 2 + len(h_type) % 2 + len(s_type) % 2 > len(c_type):
            print('IMPOSSIBLE')
        else:
            if len(d_type) % 2 == 0:
                print(*d_type)
            else:
                print(*d_type, end=' ')
                print(c_type[0])
                c_type = c_type[1:]
            if len(s_type) % 2 == 0:
                print(*s_type)
            else:
                print(*s_type, end=' ')
                print(c_type[0])
                c_type = c_type[1:]
            if len(h_type) % 2 == 0:
                print(*h_type)
            else:
                print(*h_type, end=' ')
                print(c_type[0])
                c_type = c_type[1:]
            print(*c_type, end=' ')

Solution (Python):
def solve() -> None:
    n = int(input())
    c = input()
    d = {c: []}
    for (a, b) in input().split():
        d[b] = d.get(b, []) + [int(a)]
    for k in d:
        d[k].sort()
    ans = []
    for (k, v) in d.items():
        if k == c:
            continue
        for i in range(0, len(v) - 1, 2):
            ans.append(f'{v[i]}{k} {v[i + 1]}{k}')
    i = -1
    for (k, v) in d.items():
        if k == c or not len(v) & 1:
            continue
        i += 1
        if i >= len(d[c]):
            print('IMPOSSIBLE')
            return
        ans.append(f'{v[-1]}{k} {d[c][i]}{c}')
    if len(d[c]) - i & 1:
        for j in range(i + 1, len(d[c]), 2):
            ans.append(f'{d[c][j]}{c} {d[c][j + 1]}{c}')
        print('\n'.join(ans))
    else:
        print('IMPOSSIBLE')
for _ in range(int(input())):
    solve()

Solution (Python):
""""""
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
    n = int(input())
    trump = input().strip()
    cards = input().split()
    li = [[] for _ in range(4)]
    dic = {'C': 0, 'D': 1, 'H': 2, 'S': 3}
    odd = [0] * 4
    for c in cards:
        li[dic[c[1]]].append(c)
    for d in dic:
        if d != trump and len(li[dic[d]]) % 2 == 1:
            odd[dic[d]] += 1
    c_trump = len(li[dic[trump]])
    if sum(odd) > c_trump:
        print('IMPOSSIBLE')
    else:
        for i in li:
            i.sort()
        for i in dic:
            if odd[dic[i]] == 1:
                li[dic[i]].append(li[dic[trump]].pop())
        for i in dic:
            for j in range(len(li[dic[i]]) // 2):
                print(li[dic[i]][2 * j], li[dic[i]][2 * j + 1])