#!/usr/bin/perl -w

use strict;

local $/ = "\n\n";
my @classes;
for (split /\n/, <>) {
	my (@cls) = /\A(.*): (\d+)-(\d+) or (\d+)-(\d+)/;
	print "$2:$3,$4:$5.\n";
	push @classes, \@cls;
}

$_ = <>;
my @your = /(\d+)/g;
print "Your:", join("|", @your), "\n";

my @nearby;
TICKET:
for (split /\n/, <>) {
	next if !/\d/;
	my @n = /(\d+)/g;
	NUM:
	for my $num (@n) {
		for my $r (@classes) {
			if (($num >= $r->[1] && $num <= $r->[2])
				|| $num >= $r->[3] && $num <= $r->[4]) {
				next NUM;
			}
		}
		next TICKET;
	}
	# print "nearby:", join("|", @n), "\n";
	push @nearby, \@n;
}

my %valid_cols;
for my $cls (@classes) {
	my ($name, $f1, $t1, $f2, $t2) = @$cls;
	# print "Class $name:\n";
	COL:
	for my $col (0 .. $#your) {
		# print "col $col\n";
		for my $ticket (@nearby) {
			if (($ticket->[$col] < $f1 || $ticket->[$col] > $t1)
				&& $ticket->[$col] < $f2 || $ticket->[$col] > $t2) {
				next COL;
			}
		}
		$valid_cols{$name}->{$col} = 1;
		print "$name can be $col\n";
	}
}

my $mul = 1;
LOOP:
while (keys %valid_cols) {
	for my $class (keys %valid_cols) {
		if (keys %{ $valid_cols{$class} } == 1) {
			my ($col) = keys %{ $valid_cols{$class} };
			print "$class is $col\n";
			delete $valid_cols{$class};
			for my $cl1 (keys %valid_cols) {
				delete $valid_cols{$cl1}->{$col};
			}
			$mul *= $your[$col] if $class =~ /\Adeparture/;
			next LOOP;
		}
	}
}

print "Total: $mul\n";
