First, I see no reason to avoid strict and warnings. The only overhead it adds is the clearing of the variables in each loop pass. If that's an issue, you can avoid the clearing by declaring the vars outside the loops.
IO carries a lot of overhead. Do it all at once. (The python player probably did the same thing, thus the high memory usage.)
#!/usr/bin/perl use strict; use warnings; my (@file, @tr, $prev, $cur, $f, $g); { local $/; @file = split ' ', scalar(<>); } for (1..shift(@file)) { ($prev, @tr) = reverse map [ splice(@file, 0, $_) ], 1..shift(@file); for $cur (@tr) { $g = $prev->[0]; for (0 .. $#$cur) { $cur->[$_] += ($f = $g) > ($g = $prev->[$_ + 1]) ? $f : $g; } $prev = $cur; } print "$prev->[0]\n"; }
And then, let's avoid building an AoA. It saves on building time, memory costs, and avoids the need to deref. Note that splicing/poping/shifting from the ends of an array is very efficient.
#!/usr/bin/perl use strict; use warnings; my (@file, $rows, @tr, @prev, @cur, $f, $g); { local $/; @file = split ' ', scalar(<>); } for (1..shift(@file)) { $rows = shift(@file); @tr = splice(@file, 0, $rows*($rows+1)/2); @prev = splice(@tr, -($rows--)); while ($rows) { @cur = splice(@tr, -($rows--)); $g = $prev[0]; for (0 .. $#cur) { $cur[$_] += ($f = $g) > ($g = $prev[$_ + 1]) ? $f : $g; } @prev = @cur; } print "$prev[0]\n"; }
It might be faster to calculate the index into @tr instead of copying the values into in and out. But maybe not. The hindered readability and the extra additions might cancel out the benefit.
#!/usr/bin/perl use strict; use warnings; my (@file, $rows, @tr, $prev, $cur, $f, $g); { local $/; @file = split ' ', scalar(<>); } for (1..shift(@file)) { $rows = shift(@file); @tr = splice(@file, 0, $rows*($rows+1)/2); $prev = @tr - $rows--; while ($rows) { $cur = $prev - $rows--; $g = $tr[$prev]; for (0 .. $rows) { $tr[$cur + $_] += ($f = $g) > ($g = $tr[$prev + $_ + 1]) ? $f : $g; } $prev = $cur; } print "$tr[0]\n"; }
You could do something similar to avoid creating @tr.
By the way, ($f = $g) > ($g = $prev->[$_ + 1]) is not guaranteed to be evaluated in the order in which you want it to be evaluated. It's technically a bug since operand evaluation order is undefined (although predictable and unlikely to change) in Perl.
In reply to Re: Adding a lot of small integers
by ikegami
in thread Adding a lot of small integers
by kappa
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |