#!/usr/bin/perl -w

use v5.16;

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

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

for (1 .. 10) {
	my $i = 0;
	while ($i < length $tmpl) {
		my $s = substr($tmpl, $i, 2);
		if ($r{$s}) {
			substr($tmpl, $i, 2) = $r{$s};
			$i+=2;
			next;
		}
		$i++;
	}
}

my %count;
for ('A' .. 'Z') {
	$count{$_} = () = $tmpl =~ /$_/g;
}

my @count = sort { $a <=> $b } grep { $_ > 0 } values %count;

say $count[-1] - $count[0];

