#!/usr/bin/perl -w

use v5.30;
use strict;

chomp (my $state = <>);
$state =~ s/.*: //;

scalar <>;

my %rules;
while (<>) {
	chomp;
	my ($src, $dst) = split / => /;
	$rules{$src} = $dst;
}

my $off = 0;
for (1 .. 20) {
	if ($state !~ /^\.\.\.\./) {
		$state = '....' . $state;
		$off -= 4;
		say "adding 4";
	}
	$state = $state . '....' if $state !~ /\.\.\.\.$/;

	my $nstate = $state;
	$nstate =~ y/#/./;

	for my $p (2 .. length($state)-3) {
		my $src = substr($state, $p-2, 5);
		# die "no rule for $src" if !exists $rules{$src};
		substr($nstate, $p, 1) = $rules{$src} if defined $rules{$src};
	}
	$state = $nstate;
	say $state;
}

my $sum;
while ($state =~ /#/g) {
	say "at ", pos($state) + $off - 1;
	$sum += pos($state) + $off - 1;
}
say $sum;
