Skip to content

Commit

Permalink
return the old idea of the flow from version 1, where it's the
Browse files Browse the repository at this point in the history
original graph but with the edge weights changed

changed version to 0.02

added more comments
  • Loading branch information
waltman committed Jul 23, 2007
1 parent fe8dc7f commit 0e1c51e
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions MaxFlow.pm
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use Carp 'carp';
@ISA = qw(Exporter);
@EXPORT_OK = qw(max_flow);

$VERSION = '0.01';
$VERSION = '0.02';

use strict;
use warnings;
Expand All @@ -29,28 +29,37 @@ sub max_flow {
return;
}

my $flow = init_flow($g);
my $resid = init_flow($g);

while (1) {
# find the shortest augmenting path between $source and $sink
my $path = shortest_path($g, $flow, $source, $sink);
my $path = shortest_path($g, $resid, $source, $sink);
last unless @$path;

# find min weight in path
my $min;
for my $i (0..$#$path - 1) {
my $weight = residual_capacity($g, $flow, $path->[$i], $path->[$i+1]);
my $weight = residual_capacity($g, $resid, $path->[$i], $path->[$i+1]);
$min = $weight if !defined $min || $weight < $min;
}

# update the flow network
for my $i (0..$#$path - 1) {
add_edge_weight($flow, $path->[$i], $path->[$i+1], $min);
add_edge_weight($flow, $path->[$i+1], $path->[$i], -$min);
add_edge_weight($resid, $path->[$i], $path->[$i+1], $min);
add_edge_weight($resid, $path->[$i+1], $path->[$i], -$min);
}

}

# convert the residual flow graph into a copy of the original
# graph, but with the edge weights set to the flow
my $flow = $g->copy_graph;
for my $e ($flow->edges) {
my ($u, $v) = @$e;
my $weight = $resid->get_edge_weight($u, $v);
$flow->set_edge_weight($u, $v, $weight > 0 ? $weight : 0);
}

return $flow;
}

Expand All @@ -67,7 +76,7 @@ sub init_flow {
return $flow;
}

# do a breadth-first search over edges with positive weight
# do a breadth-first search over edges with positive residual capacity
sub shortest_path {
my ($g, $flow, $from, $to) = @_;

Expand Down Expand Up @@ -108,6 +117,7 @@ sub shortest_path {
return \@path;
}

# add $delta to the weight of the edge ($u, $v)
sub add_edge_weight {
my ($g, $u, $v, $delta) = @_;

Expand Down

0 comments on commit 0e1c51e

Please sign in to comment.