#!/usr/bin/perl -w

use v5.38;

$/ = "\n\n";
my %dirs;
my @steps = split //, scalar <>;
pop @steps;
pop @steps;
my $l = <>;
for (split /\n/, $l) {
	my @x = /[A-Z]{3}/g;
	$dirs{$x[0].'L'} = $x[1];
	$dirs{$x[0].'R'} = $x[2];
}

my %seen;
my $now = 'AAA' . $steps[0];
my $i = 0;
my $n;
while ($now !~ /^ZZZ/) {
	say $now;
	$i ++;
	$i = 0 if $i >= @steps;
	$now = $dirs{$now}.$steps[$i];
	$n++;
}
say $n;
