7 list 'level_list' on the nodes on level i implemented by hand
8 stack 'active' on the active nodes on level i
9 runs heuristic 'highest label' for H1*n relabels
10 runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
12 Parameters H0 and H1 are initialized to 20 and 1.
16 Preflow(Graph, Node, Node, CapMap, FlowMap, bool) : bool must be false if
17 FlowMap is not constant zero, and should be true if it is
23 Num flowValue() : returns the value of a maximum flow
25 void minMinCut(CutMap& M) : sets M to the characteristic vector of the
26 minimum min cut. M should be a map of bools initialized to false. ??Is it OK?
28 void maxMinCut(CutMap& M) : sets M to the characteristic vector of the
29 maximum min cut. M should be a map of bools initialized to false.
31 void minCut(CutMap& M) : sets M to the characteristic vector of
32 a min cut. M should be a map of bools initialized to false.
36 #ifndef HUGO_MAX_FLOW_H
37 #define HUGO_MAX_FLOW_H
46 #include <graph_wrapper.h>
47 #include <bfs_iterator.h>
50 #include <for_each_macros.h>
55 ///\author Marton Makai, Jacint Szabo
56 template <typename Graph, typename Num,
57 typename CapMap=typename Graph::template EdgeMap<Num>,
58 typename FlowMap=typename Graph::template EdgeMap<Num> >
61 typedef typename Graph::Node Node;
62 typedef typename Graph::NodeIt NodeIt;
63 typedef typename Graph::OutEdgeIt OutEdgeIt;
64 typedef typename Graph::InEdgeIt InEdgeIt;
66 typedef typename std::vector<std::stack<Node> > VecStack;
67 typedef typename Graph::template NodeMap<Node> NNMap;
68 typedef typename std::vector<Node> VecNode;
73 const CapMap* capacity;
75 int n; //the number of nodes of G
76 typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
77 typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
78 typedef typename ResGW::Edge ResGWEdge;
79 //typedef typename ResGW::template NodeMap<bool> ReachedMap;
80 typedef typename Graph::template NodeMap<int> ReachedMap;
82 //level works as a bool map in augmenting path algorithms
83 //and is used by bfs for storing reached information.
84 //In preflow, it shows levels of nodes.
85 //typename Graph::template NodeMap<int> level;
86 typename Graph::template NodeMap<Num> excess;
90 ///\todo Document this
97 MaxFlow(const Graph& _G, Node _s, Node _t, const CapMap& _capacity,
99 g(&_G), s(_s), t(_t), capacity(&_capacity),
100 flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0) {}
102 /// A max flow algorithm is run.
103 ///\pre the flow have to be 0 at the beginning.
105 preflow( ZERO_FLOW );
108 /// A preflow algorithm is run.
109 ///\pre The initial edge-map have to be a
110 /// zero flow if \c fe is \c ZERO_FLOW,
111 /// a flow if \c fe is \c GEN_FLOW,
112 /// and a pre-flow it is \c PREFLOW.
113 void preflow( flowEnum fe ) {
118 /// Run the first phase of preflow, starting from a 0 flow, from a flow,
119 /// or from a preflow, according to \c fe.
120 void preflowPhase0( flowEnum fe );
122 /// Second phase of preflow.
123 void preflowPhase1();
125 /// Starting from a flow, this method searches for an augmenting path
126 /// according to the Edmonds-Karp algorithm
127 /// and augments the flow on if any.
128 /// The return value shows if the augmentation was succesful.
129 bool augmentOnShortestPath();
131 /// Starting from a flow, this method searches for an augmenting blockin
132 /// flow according to Dinits' algorithm and augments the flow on if any.
133 /// The blocking flow is computed in a physically constructed
134 /// residual graph of type \c Mutablegraph.
135 /// The return value show sif the augmentation was succesful.
136 template<typename MutableGraph> bool augmentOnBlockingFlow();
138 /// The same as \c augmentOnBlockingFlow<MutableGraph> but the
139 /// residual graph is not constructed physically.
140 /// The return value shows if the augmentation was succesful.
141 bool augmentOnBlockingFlow2();
143 /// Returns the actual flow value.
144 /// More precisely, it returns the negative excess of s, thus
145 /// this works also for preflows.
148 FOR_EACH_INC_LOC(OutEdgeIt, e, *g, s) a+=(*flow)[e];
149 FOR_EACH_INC_LOC(InEdgeIt, e, *g, s) a-=(*flow)[e];
153 /// Should be used between preflowPhase0 and preflowPhase1.
154 ///\todo We have to make some status variable which shows the actual state
155 /// of the class. This enables us to determine which methods are valid
156 /// for MinCut computation
157 template<typename _CutMap>
158 void actMinCut(_CutMap& M) {
160 for(g->first(v); g->valid(v); g->next(v)) {
161 if ( level[v] < n ) {
169 /// The unique inclusionwise minimum cut is computed by
170 /// processing a bfs from s in the residual graph.
171 ///\pre flow have to be a max flow otherwise it will the whole node-set.
172 template<typename _CutMap>
173 void minMinCut(_CutMap& M) {
175 std::queue<Node> queue;
180 while (!queue.empty()) {
181 Node w=queue.front();
185 for(g->first(e,w) ; g->valid(e); g->next(e)) {
187 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
194 for(g->first(f,w) ; g->valid(f); g->next(f)) {
196 if (!M[v] && (*flow)[f] > 0 ) {
205 /// The unique inclusionwise maximum cut is computed by
206 /// processing a reverse bfs from t in the residual graph.
207 ///\pre flow have to be a max flow otherwise it will be empty.
208 template<typename _CutMap>
209 void maxMinCut(_CutMap& M) {
212 for(g->first(v) ; g->valid(v); g->next(v)) {
216 std::queue<Node> queue;
221 while (!queue.empty()) {
222 Node w=queue.front();
227 for(g->first(e,w) ; g->valid(e); g->next(e)) {
229 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
236 for(g->first(f,w) ; g->valid(f); g->next(f)) {
238 if (M[v] && (*flow)[f] > 0 ) {
247 /// A minimum cut is computed.
248 template<typename CutMap>
249 void minCut(CutMap& M) { minMinCut(M); }
252 void resetSource(Node _s) { s=_s; }
254 void resetTarget(Node _t) { t=_t; }
256 /// capacity-map is changed.
257 void resetCap(const CapMap& _cap) { capacity=&_cap; }
259 /// flow-map is changed.
260 void resetFlow(FlowMap& _flow) { flow=&_flow; }
265 int push(Node w, VecStack& active) {
269 int newlevel=n; //bound on the next level of w
272 for(g->first(e,w); g->valid(e); g->next(e)) {
274 if ( (*flow)[e] >= (*capacity)[e] ) continue;
277 if( lev > level[v] ) { //Push is allowed now
279 if ( excess[v]<=0 && v!=t && v!=s ) {
281 active[lev_v].push(v);
284 Num cap=(*capacity)[e];
288 if ( remcap >= exc ) { //A nonsaturating push.
290 flow->set(e, flo+exc);
291 excess.set(v, excess[v]+exc);
295 } else { //A saturating push.
297 excess.set(v, excess[v]+remcap);
300 } else if ( newlevel > level[v] ) newlevel = level[v];
305 for(g->first(e,w); g->valid(e); g->next(e)) {
307 if( (*flow)[e] <= 0 ) continue;
310 if( lev > level[v] ) { //Push is allowed now
312 if ( excess[v]<=0 && v!=t && v!=s ) {
314 active[lev_v].push(v);
319 if ( flo >= exc ) { //A nonsaturating push.
321 flow->set(e, flo-exc);
322 excess.set(v, excess[v]+exc);
325 } else { //A saturating push.
327 excess.set(v, excess[v]+flo);
331 } else if ( newlevel > level[v] ) newlevel = level[v];
334 } // if w still has excess after the out edge for cycle
342 void preflowPreproc ( flowEnum fe, VecStack& active,
343 VecNode& level_list, NNMap& left, NNMap& right ) {
345 std::queue<Node> bfs_queue;
350 //Reverse_bfs from t, to find the starting level.
354 while (!bfs_queue.empty()) {
356 Node v=bfs_queue.front();
361 for(g->first(e,v); g->valid(e); g->next(e)) {
363 if ( level[w] == n && w != s ) {
365 Node first=level_list[l];
366 if ( g->valid(first) ) left.set(first,w);
376 for(g->first(e,s); g->valid(e); g->next(e))
378 Num c=(*capacity)[e];
379 if ( c <= 0 ) continue;
381 if ( level[w] < n ) {
382 if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
384 excess.set(w, excess[w]+c);
393 //Reverse_bfs from t in the residual graph,
394 //to find the starting level.
398 while (!bfs_queue.empty()) {
400 Node v=bfs_queue.front();
405 for(g->first(e,v); g->valid(e); g->next(e)) {
406 if ( (*capacity)[e] <= (*flow)[e] ) continue;
408 if ( level[w] == n && w != s ) {
410 Node first=level_list[l];
411 if ( g->valid(first) ) left.set(first,w);
419 for(g->first(f,v); g->valid(f); g->next(f)) {
420 if ( 0 >= (*flow)[f] ) continue;
422 if ( level[w] == n && w != s ) {
424 Node first=level_list[l];
425 if ( g->valid(first) ) left.set(first,w);
436 for(g->first(e,s); g->valid(e); g->next(e))
438 Num rem=(*capacity)[e]-(*flow)[e];
439 if ( rem <= 0 ) continue;
441 if ( level[w] < n ) {
442 if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
443 flow->set(e, (*capacity)[e]);
444 excess.set(w, excess[w]+rem);
449 for(g->first(f,s); g->valid(f); g->next(f))
451 if ( (*flow)[f] <= 0 ) continue;
453 if ( level[w] < n ) {
454 if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
455 excess.set(w, excess[w]+(*flow)[f]);
466 void relabel(Node w, int newlevel, VecStack& active,
467 VecNode& level_list, NNMap& left,
468 NNMap& right, int& b, int& k, bool what_heur )
473 Node right_n=right[w];
477 if ( g->valid(right_n) ) {
478 if ( g->valid(left_n) ) {
479 right.set(left_n, right_n);
480 left.set(right_n, left_n);
482 level_list[lev]=right_n;
483 left.set(right_n, INVALID);
486 if ( g->valid(left_n) ) {
487 right.set(left_n, INVALID);
489 level_list[lev]=INVALID;
494 if ( !g->valid(level_list[lev]) ) {
497 for (int i=lev; i!=k ; ) {
498 Node v=level_list[++i];
499 while ( g->valid(v) ) {
503 level_list[i]=INVALID;
505 while ( !active[i].empty() ) {
506 active[i].pop(); //FIXME: ezt szebben kene
518 if ( newlevel == n ) level.set(w,n);
520 level.set(w,++newlevel);
521 active[newlevel].push(w);
522 if ( what_heur ) b=newlevel;
523 if ( k < newlevel ) ++k; //now k=newlevel
524 Node first=level_list[newlevel];
525 if ( g->valid(first) ) left.set(first,w);
528 level_list[newlevel]=w;
535 template<typename MapGraphWrapper>
538 const MapGraphWrapper* g;
539 typename MapGraphWrapper::template NodeMap<int> dist;
541 DistanceMap(MapGraphWrapper& _g) : g(&_g), dist(*g, g->nodeNum()) { }
542 void set(const typename MapGraphWrapper::Node& n, int a) {
545 int operator[](const typename MapGraphWrapper::Node& n)
547 // int get(const typename MapGraphWrapper::Node& n) const {
549 // bool get(const typename MapGraphWrapper::Edge& e) const {
550 // return (dist.get(g->tail(e))<dist.get(g->head(e))); }
551 bool operator[](const typename MapGraphWrapper::Edge& e) const {
552 return (dist[g->tail(e)]<dist[g->head(e)]);
559 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
560 void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase0( flowEnum fe )
563 int heur0=(int)(H0*n); //time while running 'bound decrease'
564 int heur1=(int)(H1*n); //time while running 'highest label'
565 int heur=heur1; //starting time interval (#of relabels)
569 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
572 //Needed for 'bound decrease', true means no active nodes are above bound b.
574 int k=n-2; //bound on the highest level under n containing a node
575 int b=k; //bound on the highest level under n of an active node
579 NNMap left(*g, INVALID);
580 NNMap right(*g, INVALID);
581 VecNode level_list(n,INVALID);
582 //List of the nodes in level i<n, set to n.
585 for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
586 //setting each node to level n
591 //counting the excess
593 for(g->first(v); g->valid(v); g->next(v)) {
597 for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
599 for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
603 //putting the active nodes into the stack
605 if ( exc > 0 && lev < n && v != t ) active[lev].push(v);
611 //Counting the excess of t
615 for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
617 for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
627 preflowPreproc( fe, active, level_list, left, right );
628 //End of preprocessing
631 //Push/relabel on the highest level active nodes.
634 if ( !what_heur && !end && k > 0 ) {
640 if ( active[b].empty() ) --b;
643 Node w=active[b].top();
645 int newlevel=push(w,active);
646 if ( excess[w] > 0 ) relabel(w, newlevel, active, level_list,
647 left, right, b, k, what_heur);
650 if ( numrelabel >= heur ) {
668 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
669 void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase1()
672 int k=n-2; //bound on the highest level under n containing a node
673 int b=k; //bound on the highest level under n of an active node
677 std::queue<Node> bfs_queue;
680 while (!bfs_queue.empty()) {
682 Node v=bfs_queue.front();
687 for(g->first(e,v); g->valid(e); g->next(e)) {
688 if ( (*capacity)[e] <= (*flow)[e] ) continue;
690 if ( level[u] >= n ) {
693 if ( excess[u] > 0 ) active[l].push(u);
698 for(g->first(f,v); g->valid(f); g->next(f)) {
699 if ( 0 >= (*flow)[f] ) continue;
701 if ( level[u] >= n ) {
704 if ( excess[u] > 0 ) active[l].push(u);
714 if ( active[b].empty() ) --b;
716 Node w=active[b].top();
718 int newlevel=push(w,active);
721 if ( excess[w] > 0 ) {
722 level.set(w,++newlevel);
723 active[newlevel].push(w);
726 } // if stack[b] is nonempty
732 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
733 bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnShortestPath()
735 ResGW res_graph(*g, *capacity, *flow);
738 //ReachedMap level(res_graph);
739 FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
740 BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
741 bfs.pushAndSetReached(s);
743 typename ResGW::template NodeMap<ResGWEdge> pred(res_graph);
744 pred.set(s, INVALID);
746 typename ResGW::template NodeMap<Num> free(res_graph);
748 //searching for augmenting path
749 while ( !bfs.finished() ) {
750 ResGWOutEdgeIt e=bfs;
751 if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
752 Node v=res_graph.tail(e);
753 Node w=res_graph.head(e);
755 if (res_graph.valid(pred[v])) {
756 free.set(w, std::min(free[v], res_graph.resCap(e)));
758 free.set(w, res_graph.resCap(e));
760 if (res_graph.head(e)==t) { _augment=true; break; }
764 } //end of searching augmenting path
768 Num augment_value=free[t];
769 while (res_graph.valid(pred[n])) {
771 res_graph.augment(e, augment_value);
787 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
788 template<typename MutableGraph>
789 bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow()
791 typedef MutableGraph MG;
794 ResGW res_graph(*g, *capacity, *flow);
796 //bfs for distances on the residual graph
797 //ReachedMap level(res_graph);
798 FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
799 BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
800 bfs.pushAndSetReached(s);
801 typename ResGW::template NodeMap<int>
802 dist(res_graph); //filled up with 0's
804 //F will contain the physical copy of the residual graph
805 //with the set of edges which are on shortest paths
807 typename ResGW::template NodeMap<typename MG::Node>
808 res_graph_to_F(res_graph);
810 typename ResGW::NodeIt n;
811 for(res_graph.first(n); res_graph.valid(n); res_graph.next(n)) {
812 res_graph_to_F.set(n, F.addNode());
816 typename MG::Node sF=res_graph_to_F[s];
817 typename MG::Node tF=res_graph_to_F[t];
818 typename MG::template EdgeMap<ResGWEdge> original_edge(F);
819 typename MG::template EdgeMap<Num> residual_capacity(F);
821 while ( !bfs.finished() ) {
822 ResGWOutEdgeIt e=bfs;
823 if (res_graph.valid(e)) {
824 if (bfs.isBNodeNewlyReached()) {
825 dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
826 typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)], res_graph_to_F[res_graph.head(e)]);
827 original_edge.update();
828 original_edge.set(f, e);
829 residual_capacity.update();
830 residual_capacity.set(f, res_graph.resCap(e));
832 if (dist[res_graph.head(e)]==(dist[res_graph.tail(e)]+1)) {
833 typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)], res_graph_to_F[res_graph.head(e)]);
834 original_edge.update();
835 original_edge.set(f, e);
836 residual_capacity.update();
837 residual_capacity.set(f, res_graph.resCap(e));
842 } //computing distances from s in the residual graph
848 //computing blocking flow with dfs
849 DfsIterator< MG, typename MG::template NodeMap<bool> > dfs(F);
850 typename MG::template NodeMap<typename MG::Edge> pred(F);
851 pred.set(sF, INVALID);
852 //invalid iterators for sources
854 typename MG::template NodeMap<Num> free(F);
856 dfs.pushAndSetReached(sF);
857 while (!dfs.finished()) {
859 if (F.valid(/*typename MG::OutEdgeIt*/(dfs))) {
860 if (dfs.isBNodeNewlyReached()) {
861 typename MG::Node v=F.aNode(dfs);
862 typename MG::Node w=F.bNode(dfs);
864 if (F.valid(pred[v])) {
865 free.set(w, std::min(free[v], residual_capacity[dfs]));
867 free.set(w, residual_capacity[dfs]);
876 F.erase(/*typename MG::OutEdgeIt*/(dfs));
882 typename MG::Node n=tF;
883 Num augment_value=free[tF];
884 while (F.valid(pred[n])) {
885 typename MG::Edge e=pred[n];
886 res_graph.augment(original_edge[e], augment_value);
888 if (residual_capacity[e]==augment_value)
891 residual_capacity.set(e, residual_capacity[e]-augment_value);
905 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
906 bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow2()
910 ResGW res_graph(*g, *capacity, *flow);
912 //ReachedMap level(res_graph);
913 FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
914 BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
916 bfs.pushAndSetReached(s);
917 DistanceMap<ResGW> dist(res_graph);
918 while ( !bfs.finished() ) {
919 ResGWOutEdgeIt e=bfs;
920 if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
921 dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
924 } //computing distances from s in the residual graph
926 //Subgraph containing the edges on some shortest paths
927 ConstMap<typename ResGW::Node, bool> true_map(true);
928 typedef SubGraphWrapper<ResGW, ConstMap<typename ResGW::Node, bool>,
929 DistanceMap<ResGW> > FilterResGW;
930 FilterResGW filter_res_graph(res_graph, true_map, dist);
932 //Subgraph, which is able to delete edges which are already
934 typename FilterResGW::template NodeMap<typename FilterResGW::OutEdgeIt>
935 first_out_edges(filter_res_graph);
936 typename FilterResGW::NodeIt v;
937 for(filter_res_graph.first(v); filter_res_graph.valid(v);
938 filter_res_graph.next(v))
940 typename FilterResGW::OutEdgeIt e;
941 filter_res_graph.first(e, v);
942 first_out_edges.set(v, e);
944 typedef ErasingFirstGraphWrapper<FilterResGW, typename FilterResGW::
945 template NodeMap<typename FilterResGW::OutEdgeIt> > ErasingResGW;
946 ErasingResGW erasing_res_graph(filter_res_graph, first_out_edges);
953 //computing blocking flow with dfs
954 DfsIterator< ErasingResGW,
955 typename ErasingResGW::template NodeMap<bool> >
956 dfs(erasing_res_graph);
957 typename ErasingResGW::
958 template NodeMap<typename ErasingResGW::OutEdgeIt>
959 pred(erasing_res_graph);
960 pred.set(s, INVALID);
961 //invalid iterators for sources
963 typename ErasingResGW::template NodeMap<Num>
964 free1(erasing_res_graph);
966 dfs.pushAndSetReached(
967 typename ErasingResGW::Node(
968 typename FilterResGW::Node(
969 typename ResGW::Node(s)
973 while (!dfs.finished()) {
975 if (erasing_res_graph.valid(
976 typename ErasingResGW::OutEdgeIt(dfs)))
978 if (dfs.isBNodeNewlyReached()) {
980 typename ErasingResGW::Node v=erasing_res_graph.aNode(dfs);
981 typename ErasingResGW::Node w=erasing_res_graph.bNode(dfs);
983 pred.set(w, /*typename ErasingResGW::OutEdgeIt*/(dfs));
984 if (erasing_res_graph.valid(pred[v])) {
985 free1.set(w, std::min(free1[v], res_graph.resCap(
986 typename ErasingResGW::OutEdgeIt(dfs))));
988 free1.set(w, res_graph.resCap(
989 typename ErasingResGW::OutEdgeIt(dfs)));
998 erasing_res_graph.erase(dfs);
1004 typename ErasingResGW::Node n=typename FilterResGW::Node(typename ResGW::Node(t));
1005 // typename ResGW::NodeMap<Num> a(res_graph);
1006 // typename ResGW::Node b;
1008 // typename FilterResGW::NodeMap<Num> a1(filter_res_graph);
1009 // typename FilterResGW::Node b1;
1011 // typename ErasingResGW::NodeMap<Num> a2(erasing_res_graph);
1012 // typename ErasingResGW::Node b2;
1014 Num augment_value=free1[n];
1015 while (erasing_res_graph.valid(pred[n])) {
1016 typename ErasingResGW::OutEdgeIt e=pred[n];
1017 res_graph.augment(e, augment_value);
1018 n=erasing_res_graph.tail(e);
1019 if (res_graph.resCap(e)==0)
1020 erasing_res_graph.erase(e);
1024 } //while (__augment)
1034 #endif //HUGO_MAX_FLOW_H