#!/usr/bin/perl -w

use v5.38;

chomp(my $steps = <>);
my @steps = split //, $steps;

scalar <>;

my %dirs;
while (<>) {
	my @x = /\w{3}/g;
	$dirs{$x[0].'L'} = $x[1];
	$dirs{$x[0].'R'} = $x[2];
}

my $now = 'AAA';
my $i = 0;
while ($now ne 'ZZZ') {
	$now = $dirs{$now . ($steps[$i++ % @steps])};
}
say $i;
