#!/usr/bin/perl -w

use v5.16;
use Data::Dumper;

my (@m, @v);
while (<>) {
	my @row = /-?\d+/g;
	push @m, [ @row ];
	push @v, [ 0, 0, 0];
}

my @states;
my $rep = 0;
my @reps;
my $i = 0;
while (1) {
	for my $m1 (0 .. $#m) {
	for my $m2 (0 .. $#m) {
		next if $m1 == $m2;
		for my $c (0 .. 2) {
			$v[$m1][$c]++ if $m[$m1][$c] < $m[$m2][$c];
			$v[$m1][$c]-- if $m[$m1][$c] > $m[$m2][$c];
		}
	} }
	for my $m1 (0 .. $#m) {
		for my $c (0 .. 2) {
			$m[$m1][$c] += $v[$m1][$c];
		}
	}
	for my $c (0 .. 2) {
		next if $reps[$c];
		my $state = join(',', (map { $_->[$c] } @m), (map { $_->[$c] } @v));
		next unless $states[$c]->{$state}++;
		$reps[$c] = $i;
		$rep++;
	}
	last if $rep > 2;
	$i++;
}

sub gcd {
	my ($n1, $n2) = @_;
	while ($n1 != $n2) {
		($n1, $n2) = ($n2, $n1) if $n1 < $n2;
		$n1 -= $n2;
	}
	return $n1;
}

say "reps: ", join(',', @reps);
my $m = $reps[0]*$reps[1]/gcd($reps[0], $reps[1]);
$m = $m*$reps[2]/gcd($m, $reps[2]);
say $m;

my $sum;
for my $m1 (0 .. $#m) {
	my ($pot, $kin);
	for my $c (0 .. 2) {
		$pot += abs($m[$m1][$c]);
		$kin += abs($v[$m1][$c]);
	}
	$sum += $pot*$kin;
}

say $sum;
		


