#!/usr/bin/perl -w

use v5.38;

my %cards;
while (<>) {
	chomp;
	my ($card, $bid) = split /\s+/;
	$cards{$card} = $bid;
	say " $card => $bid $_ " . val($card);
}

sub rank {
	my $card = shift;
	my @cards = split //, $card;
	my %hist;
	$hist{$_}++ for @cards;
	return 1 if grep { $hist{$_} == 5 } @cards;
	return 2 if grep { $hist{$_} == 4 } @cards;
	return 3 if grep { $hist{$_} == 3 } @cards
		and grep { $hist{$_} == 2 } @cards;
	return 4 if grep { $hist{$_} == 3 } @cards;
	return 5 if (grep { $hist{$_} == 2 } @cards) == 4;
	return 6 if grep { $hist{$_} == 2 } @cards;
	return 7;
}

sub val {
	my $val = shift;
	$val =~ y/AKQJT98765432/ABCDEFGHIJKLM/;
	return rank($val).$val;
}

my $i = 1;
my $sum;
for my $card (sort { val($b) cmp val($a) } keys %cards) {
	say "$card $i ", val($card);
	$sum += $cards{$card} * $i++;
}

say $sum;

