# pyright: strict from collections import Counter from collections.abc import Callable from sys import stdin from typing import TypeAlias Hand: TypeAlias = tuple[int, int, int, int, int] def parse_hand(card_worth: dict[str, int], hand: str) -> Hand: ret = tuple(card_worth[c] for c in hand) if len(ret) != 5: raise ValueError return ret def hand_type(c: list[tuple[int, int]]) -> int: if c[0][1] == 5: return 6 if c[0][1] == 4: return 5 if c[0][1] == 3 and c[1][1] == 2: return 4 if c[0][1] == 3: return 3 if c[0][1] == 2 and c[1][1] == 2: return 2 if c[0][1] == 2: return 1 return 0 def solve( cards: str, inp: list[tuple[str, int]], fudge_count: Callable[[Counter[int]], Counter[int]] = lambda x: x, ) -> int: card_worth = {c: i for i, c in enumerate(reversed(cards))} return sum( rank * bid for rank, (_, bid) in enumerate( sorted( ((parse_hand(card_worth, hand), bid) for hand, bid in inp), key=lambda i: ( hand_type(fudge_count(Counter(i[0])).most_common()), i[0], ), ), start=1, ) ) def p2_fudge(c: Counter[int]) -> Counter[int]: if 0 in c and c[0] != 5: target = next(e[0] for e in c.most_common() if e[0] != 0) c[target] += c[0] c[0] = 0 return c inp = [(l[0], int(l[1])) for l in (l.rstrip().split() for l in stdin)] print(solve("AKQJT98765432", inp)) print(solve("AKQT98765432J", inp, fudge_count=p2_fudge))