Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- # coded by Sergei Kirjanov
- # with advice from the team :)
- use strict;
- my %w; # $w{node_name} is node_weight
- my %p; # $p{node_name} is node_parent_name
- my %h; # for heavy $h{branch_root_name} is branch_weight
- my %l; # for light $l{branch_root_name} is branch_weight
- my %has; # $has{branch_root_name}{node_name} is 1 if node is in branch
- my @res; # branch_root cutting seq
- my($bs,@in) = <STDIN>;
- $bs=~/^buffer\=(\d+)/ and $bs=$1 or die $bs;
- # parsing node info:
- /(\w),(\d+),((\w)|\-)/ and ($w{$1},$p{$1})=($2,$4) or die "{$_}" for @in;
- # precalculating for branches (branch for every node)
- for(keys %p){
- for(my $c=$_;$c;$c=$p{$c}){
- $h{$c} += $w{$_};
- $has{$c}{$_} = 1;
- }
- }
- $h{$_}<=$bs and $l{$_} = delete $h{$_} for keys %h;
- # cut optimal branches from tree, one by one
- # I can not proove this will be truely the optimal method
- while(1){
- my($n,$w); # chosen node_name and weight
- # choose heaviest of light branches
- # %l should be replaced by some autosorting structure for big trees
- $l{$_}>$w and ($n,$w)=($_,$l{$_}) and $w==$bs and last for keys %l;
- push @res, $n||last;
- delete @l{keys %{$has{$n}}}; # remove branch nodes
- # reduce weights of parents
- $h{$n}-=$w, $h{$n}<=$bs and $l{$n} = delete $h{$n} while $n=$p{$n};
- }
- print @res, %h ? " - stop\n":" - ok\n";
Advertisement
Add Comment
Please, Sign In to add comment