#!/usr/bin/perl -w

use v5.38;
use experimental 'multidimensional';
$; = ';';

my @bricks = map { [ /\d+/g ] } <>;
my %seen;
sub set_brick {
	my ($b) = @_;

	for my $x ($b->[0] .. $b->[3]) {
	for my $y ($b->[1] .. $b->[4]) {
	for my $z ($b->[2] .. $b->[5]) {
		$seen{$x,$y,$z} = 1;
	} } }
}

sub clr_brick {
	my ($b) = @_;

	for my $x ($b->[0] .. $b->[3]) {
	for my $y ($b->[1] .. $b->[4]) {
	for my $z ($b->[2] .. $b->[5]) {
		undef $seen{$x,$y,$z};
	} } }
}

sub can_fall {
	my ($b) = @_;

	return undef if !$b->[2];
	my $z = $b->[2]-1;

	for my $x ($b->[0] .. $b->[3]) {
	for my $y ($b->[1] .. $b->[4]) {
		return undef if $seen{$x,$y,$z};
	} }
	return 1;
}

set_brick($_) for @bricks;

while (1) {
	my $fallen;
	my $i = 0;
	for my $b (@bricks) {
		$i++;
		next if !can_fall($b);
		# say "falling $i (@$b)";
		clr_brick($b);
		$b->[2]--; $b->[5]--;
		set_brick($b);
		# say "fallen  $i (@$b)";
		$fallen++;
	}
	last if !$fallen;
}

my $sum;
SBRICK:
for my $bi0 (0 .. $#bricks) {
	my @bricks1 = map { [ @$_ ] } @bricks;
	splice @bricks1, $bi0, 1;
	%seen = ();
	set_brick($_) for @bricks1;
	my %f;
	while (1) {
		my $fallen;
		my $i = 0;
		for my $bi1 (0 .. $#bricks1) {
			my $b1 = $bricks1[$bi1];
			next if !can_fall($b1);
			# say "falling $i (@$b1)";
			clr_brick($b1);
			$b1->[2]--; $b1->[5]--;
			set_brick($b1);
			# say "fallen  $bi1 (@$b1)";
			$fallen++;
			$f{$bi1}++;
		}
		last if !$fallen;
	}
	# say "falling $bi0 (@{ $bricks[$bi0] }) falls ", join(',',sort keys %f);
	$sum += keys %f;
}

say $sum;
