fork download
  1. #!/usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. $\ = $/;
  7.  
  8. while(<>){
  9. my( $r, $n ) = split;
  10. @_ = map ~~<>, 1 .. $r + 3;
  11. chomp @_;
  12.  
  13. my $next_to_exit = 0;
  14. my $distance_to_exit = 0;
  15.  
  16. my $LR_balance = 0;
  17.  
  18. for( @_ ){
  19. /^\./ and $distance_to_exit = 0;
  20.  
  21. $next_to_exit = 1 == $distance_to_exit ? 1 : 0;
  22.  
  23. my $minuses = () = /-/g;
  24.  
  25. while( /#/g ){
  26. $LR_balance += 6 <=> pos;
  27. }
  28.  
  29. $_ = {
  30. line => $_,
  31. next_to_exit => $next_to_exit,
  32. distance_to_exit => $distance_to_exit,
  33. minuses => $minuses,
  34. };
  35.  
  36. $distance_to_exit ++;
  37. }
  38.  
  39. for( reverse @_ ){
  40. $_->{ line } =~ /^\./ and $distance_to_exit = 0;
  41.  
  42. $_->{ distance_to_exit } > $distance_to_exit and
  43. $_->{ distance_to_exit } = $distance_to_exit;
  44.  
  45. $distance_to_exit ++;
  46. }
  47.  
  48. for my $lett ( ('a' .. 'z')[ 0 .. $n - 1 ] ){
  49.  
  50. my @sorted = sort { 0
  51. || $b->{ next_to_exit } * !! $b->{ minuses } <=> $a->{ next_to_exit } * !! $a->{ minuses }
  52. || $b->{ minuses } <=> $a->{ minuses }
  53. || $a->{ distance_to_exit } <=> $b->{ distance_to_exit }
  54. } @_;
  55.  
  56. my $ref = shift @sorted;
  57.  
  58. for my $pos ( map { 6 + $_ * ( $LR_balance <=> .5 ) } map { $_, -$_ } 1, 3, 5, 0, 4 ){
  59. ( substr $ref->{ line }, $pos - 1, 1 ) =~ s/-/$lett/ and do {
  60. $ref->{ minuses } --;
  61. $LR_balance -= $pos <=> 6;
  62. last;
  63. };
  64. }
  65. }
  66.  
  67. print $_->{ line } for @_;
  68. }
  69.  
Success #stdin #stdout 0s 18256KB
stdin
2 17
...........
---.#--.---
...........
---.---.---
...........
6 26
...........
---.---.###
#-#.---.---
---.###.---
...........
---.###.---
#--.#-#.--#
#--.--#.#-#
...........
8 6
...........
###.###.###
###.###.##-
###.###.##-
###.###.##-
...........
###.###.###
###.###.##-
###.###.##-
###.###.##-
...........
14 12
...........
###.###.###
###.###.##-
###.###.##-
###.###.##-
###.###.##-
###.###.##-
###.###.##-
...........
###.###.###
###.###.##-
###.###.##-
###.###.##-
###.###.##-
###.###.##-
###.###.##-
...........
stdout
...........
hnd.#lb.fpj
...........
kqg.cma.eoi
...........
...........
gke.aic.###
#-#.mzo.r-v
x-p.###.n-t
...........
fjb.###.dlh
#-s.#-#.w-#
#-u.qy#.#-#
...........
...........
###.###.###
###.###.##c
###.###.##d
###.###.##a
...........
###.###.###
###.###.##e
###.###.##f
###.###.##b
...........
...........
###.###.###
###.###.##c
###.###.##g
###.###.##k
###.###.##h
###.###.##d
###.###.##a
...........
###.###.###
###.###.##e
###.###.##i
###.###.##l
###.###.##j
###.###.##f
###.###.##b
...........