+#!/usr/bin/perl -w
+
+use v5.16;
+use List::Util qw(sum0);
+
+chomp (my $tmpl = <>);
+scalar <>;
+
+my (%r1, %r2, %ins);
+while (<>) {
+ chomp;
+ my ($s1, $s2, $d) = /([A-Z])/g;
+ $r1{"$s1$s2"} = "$s1$d";
+ $r2{"$s1$s2"} = "$d$s2";
+ $ins{"$s1$s2"} = $d;
+}
+
+my %count;
+my %p;
+for my $i (0 .. length($tmpl) - 2) {
+ $p{substr($tmpl, $i, 2)}++;
+ $count{substr($tmpl, $i, 1)}++;
+}
+$count{substr($tmpl, -1, 1)}++;
+
+for (1 .. 40) {
+ my %p1;
+ for my $pair (keys %p) {
+ if ($r1{$pair}) {
+ $p1{$r1{$pair}} += $p{$pair};
+ $p1{$r2{$pair}} += $p{$pair};
+ $count{$ins{$pair}} += $p{$pair};
+ }
+ }
+ %p = %p1;
+}
+
+my @count = sort { $a <=> $b } values %count;
+
+say $count[-1] - $count[0];
+