#!/usr/bin/perl -w

use v5.38;

my %cards = map { /(\S+)/g } <>;

sub rank {
	my %hist;
	$hist{$_}++ for split //, shift;
	my %rh;
	$rh{$_}++ for values %hist;
	return 1 if $rh{5};
	return 2 if $rh{4};
	return 3 if $rh{3} && $rh{2};
	return 4 if $rh{3};
	return 5 if $rh{2} && $rh{2} == 2;
	return 6 if $rh{2};
	return 7;
}

sub val {
	my $val = shift;
	my $r = rank2($val);
	$val =~ y/AKQT98765432J/ABCDEFGHIJKLM/;
	return $r.$val;
}

sub rank2 {
	my $card = shift;
	my $max_rank = rank($card);
	for my $c (split //, $card) {
		my $c1 = $card;
		$c1 =~ s/J/$c/g;
		my $r = rank($c1);
		$max_rank = $r if $r < $max_rank;
	}
	return $max_rank;
}

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

say $sum;

