#!/usr/bin/perl use strict; use warnings; my @text; while () { my ($q, $w) = split; push @{ $text[$q-1] }, $w; } my @best = calc(\@text); print "{@best}\n"; sub calc { my ($t) = @_; my @best = (0); iter($t, [(0) x 26], \@best, 0); return @best; } sub iter { my ($t, $tmp, $best, $i) = @_; if ($i == @$t) { my $s = 0; $s += $_ * ($_+1) / 2 for @$tmp[0..25]; @$best = ($s, @$tmp[26..$#$tmp]) if $s > $best->[0]; return; } for (@{ $t->[$i] }) { $tmp->[ord($_) - ord('a')]++ for split //; push @$tmp, $_; iter($t, $tmp, $best, $i+1); pop @$tmp; $tmp->[ord($_) - ord('a')]-- for split //; } }