#!/usr/bin/perl -w

use v5.16;

chomp (my $tmpl = <>);
scalar <>;

my %rules;
while (<>) {
	chomp;
	my ($s1, $s2, $d) = /[A-Z]/g;
	$rules{"$s1$s2"} = [ "$s1$d", "$d$s2", $d ];
}

my (%pairs, %count);
for my $i (0 .. length($tmpl) - 2) {
	$pairs{substr($tmpl, $i, 2)}++;
	$count{substr($tmpl, $i, 1)}++;
}
$count{substr($tmpl, -1, 1)}++;

for (1 .. 40) {
	my %newp;
	for my $pair (grep { $rules{$_} } keys %pairs) {
		my $rule = $rules{$pair};
		 $newp{ $rule->[0] } += $pairs{$pair};
		 $newp{ $rule->[1] } += $pairs{$pair};
		$count{ $rule->[2] } += $pairs{$pair};
	}
	%pairs = %newp;
}

my @count = sort { $a <=> $b } values %count;
say $count[-1] - $count[0];

