+sub add {
+ $_ = "[$_[0],$_[1]]";
+ my $modified;
+ do {
+ $modified = undef;
+ my ($i, $depth) = (0, 0);
+ while ($i < length) {
+ $depth-- if substr($_, $i, 1) eq ']';
+ $depth++ if substr($_, $i, 1) eq '[';
+
+ if ($depth >= 5) {
+ pos = $i;
+ next unless s/\G\[(\d+),(\d+)\]/X/;
+ my ($l, $r) = ($1, $2);
+ s/(\d+)([^\d]*X)/($1+$l).$2/e;
+ s/(X[^\d]*)(\d+)/$1.($2+$r)/e;
+ s/X/0/;
+ $modified++; $depth--;
+ }
+ $i++;
+ }
+ $modified++ if s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e;
+ } while ($modified);
+ return $_;
+}
+
+sub magnitude { $_ = shift; 1 while s/\[(\d+),(\d+)\]/3*$1+2*$2/e; $_ }
+
+use List::Util qw(reduce);
+
+chomp (my @nums = <>);
+
+say magnitude( reduce { add($a, $b) } @nums );