#!/usr/bin/perl
use 5.016;
use warnings;
use List
::Util qw(first max reduce
); use Data::Dumper;
local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0;
sub combi {
my ($n, $s, $r) = @_;
combi($n - 1, [@{$s}[$_ + 1 .. $#{$s}]], [@{$r}, $s->[$_]])
} (0 .. $#{$s});
}
sub del { [@{$_[0]}[0 .. $_[1] - 1, $_[1] + 1 .. $#{$_[0]}]] }
sub find { first{ $_[0]->[$_]->[0] eq $_[1]->[0] } (0 .. $#{$_[0]}) }
sub diff {
reduce{
sub{ defined $_[0] ? del
($a, $_[0]) : $a }->(find
($a, $b)) } $_[0], @{$_[1]}
}
sub go_end {
my ($s, $e, $t, $r) = @_;
go_start(
diff($s, $_),
[@{$e}, @{$_}],
$t + max
(map{ $_->[1] } @{$_}), [@{$r}, [map{ $_->[0] } @{$_}]] )
} combi(2, $s, []);
}
sub go_start {
my ($s, $e, $t, $r) = @_;
(@{$s} > 0) or return [$t, $r];
go_end(
[@{$s}, $_],
diff($e, [$_]),
$t + $_->[1],
[@{$r}, $_->[0]]
)
} @{$e};
}
sub f {
reduce{$b->[0] < $a->[0] ? $b : $a } go_end([@_], [], 0, [])
}
say Dumper(f(['A', 1], ['B', 2], ['C', 5], ['D', 10]));
IyEvdXNyL2Jpbi9wZXJsCnVzZSA1LjAxNjsKdXNlIHdhcm5pbmdzOwp1c2UgTGlzdDo6VXRpbCBxdyhmaXJzdCBtYXggcmVkdWNlKTsKdXNlIERhdGE6OkR1bXBlcjsKbG9jYWwgJERhdGE6OkR1bXBlcjo6VGVyc2UgPSAxOwpsb2NhbCAkRGF0YTo6RHVtcGVyOjpJbmRlbnQgPSAwOwoKc3ViIGNvbWJpIHsKCW15ICgkbiwgJHMsICRyKSA9IEBfOwoKCSgkbiA+IDApIG9yIHJldHVybiAkcjsKCglyZXR1cm4gbWFwewoJCWNvbWJpKCRuIC0gMSwgW0B7JHN9WyRfICsgMSAuLiAkI3skc31dXSwgW0B7JHJ9LCAkcy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