#!/usr/bin/perl -w

use v5.38;
use experimental 'for_list';
use List::Util qw(sum);

my %wfl;
while (<>) {
	chomp;
	last if !length;
	my ($name, $rest) = /(\w+)\{(\S+)\}/;
	my @rules;
	for my $r (split /,/, $rest) {
		my ($id, $op, $val, $rule) = $r =~ /(\w+)(?:(\W)(\d+):(\w+))?/;
		push @rules, [ $id, $op, $val, $rule ];
	}
	$wfl{$name} = \@rules;
}

my @parts;
while (<>) {
	my %p;
	for my ($id, $val) (/(\w)=(\d+)/g) {
		$p{$id} = $val;
	}
	push @parts, \%p;
}

sub evaluate {
	my ($part, $name) = @_;
	my %seen;
NEWWFL:
	return 0 if $seen{$name}++;
	if ($name eq 'R') {
		return 0;
	} elsif ($name eq 'A') {
		return sum values %$part;
	}
	my $w = $wfl{$name};
	for my $rule (@$w) {
		my ($id, $op, $val, $nxt) = @$rule;

		if (!defined $op) {
			$name = $id;
			goto NEWWFL;
		} else {
			if ($op eq '<') {
				if ($part->{$id} < $val) {
					$name = $nxt;
					goto NEWWFL;
				}
			}
			if ($op eq '>') {
				if ($part->{$id} > $val) {
					$name = $nxt;
					goto NEWWFL;
				}
			}
		}
	}
}

say sum map { evaluate($_, 'in') } @parts;
