#!/usr/bin/perl -w

use v5.16;

$; = ',';
sub walk {
	my ($desc) = @_;
	my %rv;
	my ($x, $y) = (0, 0);
	my $l = 0;
	for my $step (split /,/, $desc) {
		my ($dir, $dist) = $step =~ /([A-Z])(\d+)/;
		my ($dx, $dy);
		($dx, $dy) = (1,  0) if $dir eq 'R';
		($dx, $dy) = (0,  1) if $dir eq 'D';
		($dx, $dy) = (0, -1) if $dir eq 'U';
		($dx, $dy) = (-1, 0) if $dir eq 'L';
		while ($dist--) {
			$x += $dx; $y += $dy; ++$l;
			$rv{$x, $y} //= $l;
		}
		say "$step -> $x, $y ($rv{$x,$y})";
	}
	return \%rv;
}

my $p1 = walk(scalar <>);
my $p2 = walk(scalar <>);

my $dist;
for my $pos (keys %$p1) {
	next if !$p2->{$pos};
	next if $pos eq '0,0';
	my $d = $p1->{$pos}+$p2->{$pos};
	say "Intersection at $pos dist $d";
	$dist = $d if !$dist || $dist > $d;
}

say $dist;
	
