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;
96 MaxFlow(const Graph& _G, Node _s, Node _t, const CapMap& _capacity,
98 g(&_G), s(_s), t(_t), capacity(&_capacity),
99 flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0) {}
101 /// A max flow algorithm is run.
102 ///\pre the flow have to be 0 at the beginning.
104 preflow( ZERO_FLOW );
107 /// A preflow algorithm is run. The initial edge-set have to be a flow,
108 /// or from a preflow, according to \c fe.
109 void preflow( flowEnum fe ) {
114 /// Run the first phase of preflow, starting from a 0 flow, from a flow,
115 /// or from a preflow, according to \c fe.
116 void preflowPhase0( flowEnum fe );
118 /// Second phase of preflow.
119 void preflowPhase1();
121 /// Starting from a flow, this method searches for an augmenting path
122 /// according to the Edmonds-Karp algorithm
123 /// and augments the flow on if any.
124 bool augmentOnShortestPath();
126 /// Starting from a flow, this method searches for an augmenting blockin
127 /// flow according to Dinits' algorithm and augments the flow on if any.
128 /// The blocking flow is computed in a physically constructed
129 /// residual graph of type \c Mutablegraph.
130 template<typename MutableGraph> bool augmentOnBlockingFlow();
132 /// The same as \c augmentOnBlockingFlow<MutableGraph> but the
133 /// residual graph is not constructed physically.
134 bool augmentOnBlockingFlow2();
136 /// Returns the actual flow value.
137 /// More precisely, it returns the negative excess of s, thus
138 /// this works also for preflows.
141 FOR_EACH_INC_LOC(OutEdgeIt, e, *g, s) a+=(*flow)[e];
142 FOR_EACH_INC_LOC(InEdgeIt, e, *g, s) a-=(*flow)[e];
146 /// Should be used between preflowPhase0 and preflowPhase1.
147 ///\todo We have to make some status variable which shows the actual state
148 /// of the class. This enables us to determine which methods are valid
149 /// for MinCut computation
150 template<typename _CutMap>
151 void actMinCut(_CutMap& M) {
153 for(g->first(v); g->valid(v); g->next(v)) {
154 if ( level[v] < n ) {
163 /// The unique inclusionwise minimum cut is computed by
164 /// processing a bfs from s in the residual graph.
165 ///\pre flow have to be a max flow otherwise it will the whole node-set.
166 template<typename _CutMap>
167 void minMinCut(_CutMap& M) {
169 std::queue<Node> queue;
174 while (!queue.empty()) {
175 Node w=queue.front();
179 for(g->first(e,w) ; g->valid(e); g->next(e)) {
181 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
188 for(g->first(f,w) ; g->valid(f); g->next(f)) {
190 if (!M[v] && (*flow)[f] > 0 ) {
199 /// The unique inclusionwise maximum cut is computed by
200 /// processing a reverse bfs from t in the residual graph.
201 ///\pre flow have to be a max flow otherwise it will be empty.
202 template<typename _CutMap>
203 void maxMinCut(_CutMap& M) {
206 for(g->first(v) ; g->valid(v); g->next(v)) {
210 std::queue<Node> queue;
215 while (!queue.empty()) {
216 Node w=queue.front();
221 for(g->first(e,w) ; g->valid(e); g->next(e)) {
223 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
230 for(g->first(f,w) ; g->valid(f); g->next(f)) {
232 if (M[v] && (*flow)[f] > 0 ) {
241 /// A minimum cut is computed.
242 template<typename CutMap>
243 void minCut(CutMap& M) { minMinCut(M); }
246 void resetSource(Node _s) {s=_s;}
248 void resetTarget(Node _t) {t=_t;}
250 /// capacity-map is changed.
251 void resetCap(const CapMap& _cap) { capacity=&_cap; }
253 /// flow-map is changed.
254 void resetFlow(FlowMap& _flow) { flow=&_flow; }
259 int push(Node w, VecStack& active) {
263 int newlevel=n; //bound on the next level of w
266 for(g->first(e,w); g->valid(e); g->next(e)) {
268 if ( (*flow)[e] >= (*capacity)[e] ) continue;
271 if( lev > level[v] ) { //Push is allowed now
273 if ( excess[v]<=0 && v!=t && v!=s ) {
275 active[lev_v].push(v);
278 Num cap=(*capacity)[e];
282 if ( remcap >= exc ) { //A nonsaturating push.
284 flow->set(e, flo+exc);
285 excess.set(v, excess[v]+exc);
289 } else { //A saturating push.
291 excess.set(v, excess[v]+remcap);
294 } else if ( newlevel > level[v] ) newlevel = level[v];
299 for(g->first(e,w); g->valid(e); g->next(e)) {
301 if( (*flow)[e] <= 0 ) continue;
304 if( lev > level[v] ) { //Push is allowed now
306 if ( excess[v]<=0 && v!=t && v!=s ) {
308 active[lev_v].push(v);
313 if ( flo >= exc ) { //A nonsaturating push.
315 flow->set(e, flo-exc);
316 excess.set(v, excess[v]+exc);
319 } else { //A saturating push.
321 excess.set(v, excess[v]+flo);
325 } else if ( newlevel > level[v] ) newlevel = level[v];
328 } // if w still has excess after the out edge for cycle
336 void preflowPreproc ( flowEnum fe, VecStack& active,
337 VecNode& level_list, NNMap& left, NNMap& right ) {
339 std::queue<Node> bfs_queue;
344 //Reverse_bfs from t, to find the starting level.
348 while (!bfs_queue.empty()) {
350 Node v=bfs_queue.front();
355 for(g->first(e,v); g->valid(e); g->next(e)) {
357 if ( level[w] == n && w != s ) {
359 Node first=level_list[l];
360 if ( g->valid(first) ) left.set(first,w);
370 for(g->first(e,s); g->valid(e); g->next(e))
372 Num c=(*capacity)[e];
373 if ( c <= 0 ) continue;
375 if ( level[w] < n ) {
376 if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
378 excess.set(w, excess[w]+c);
387 //Reverse_bfs from t in the residual graph,
388 //to find the starting level.
392 while (!bfs_queue.empty()) {
394 Node v=bfs_queue.front();
399 for(g->first(e,v); g->valid(e); g->next(e)) {
400 if ( (*capacity)[e] <= (*flow)[e] ) continue;
402 if ( level[w] == n && w != s ) {
404 Node first=level_list[l];
405 if ( g->valid(first) ) left.set(first,w);
413 for(g->first(f,v); g->valid(f); g->next(f)) {
414 if ( 0 >= (*flow)[f] ) continue;
416 if ( level[w] == n && w != s ) {
418 Node first=level_list[l];
419 if ( g->valid(first) ) left.set(first,w);
430 for(g->first(e,s); g->valid(e); g->next(e))
432 Num rem=(*capacity)[e]-(*flow)[e];
433 if ( rem <= 0 ) continue;
435 if ( level[w] < n ) {
436 if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
437 flow->set(e, (*capacity)[e]);
438 excess.set(w, excess[w]+rem);
443 for(g->first(f,s); g->valid(f); g->next(f))
445 if ( (*flow)[f] <= 0 ) continue;
447 if ( level[w] < n ) {
448 if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
449 excess.set(w, excess[w]+(*flow)[f]);
460 void relabel(Node w, int newlevel, VecStack& active,
461 VecNode& level_list, NNMap& left,
462 NNMap& right, int& b, int& k, bool what_heur )
467 Node right_n=right[w];
471 if ( g->valid(right_n) ) {
472 if ( g->valid(left_n) ) {
473 right.set(left_n, right_n);
474 left.set(right_n, left_n);
476 level_list[lev]=right_n;
477 left.set(right_n, INVALID);
480 if ( g->valid(left_n) ) {
481 right.set(left_n, INVALID);
483 level_list[lev]=INVALID;
488 if ( !g->valid(level_list[lev]) ) {
491 for (int i=lev; i!=k ; ) {
492 Node v=level_list[++i];
493 while ( g->valid(v) ) {
497 level_list[i]=INVALID;
499 while ( !active[i].empty() ) {
500 active[i].pop(); //FIXME: ezt szebben kene
512 if ( newlevel == n ) level.set(w,n);
514 level.set(w,++newlevel);
515 active[newlevel].push(w);
516 if ( what_heur ) b=newlevel;
517 if ( k < newlevel ) ++k; //now k=newlevel
518 Node first=level_list[newlevel];
519 if ( g->valid(first) ) left.set(first,w);
522 level_list[newlevel]=w;
529 template<typename MapGraphWrapper>
532 const MapGraphWrapper* g;
533 typename MapGraphWrapper::template NodeMap<int> dist;
535 DistanceMap(MapGraphWrapper& _g) : g(&_g), dist(*g, g->nodeNum()) { }
536 void set(const typename MapGraphWrapper::Node& n, int a) {
539 int operator[](const typename MapGraphWrapper::Node& n)
541 // int get(const typename MapGraphWrapper::Node& n) const {
543 // bool get(const typename MapGraphWrapper::Edge& e) const {
544 // return (dist.get(g->tail(e))<dist.get(g->head(e))); }
545 bool operator[](const typename MapGraphWrapper::Edge& e) const {
546 return (dist[g->tail(e)]<dist[g->head(e)]);
553 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
554 void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase0( flowEnum fe )
557 int heur0=(int)(H0*n); //time while running 'bound decrease'
558 int heur1=(int)(H1*n); //time while running 'highest label'
559 int heur=heur1; //starting time interval (#of relabels)
563 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
566 //Needed for 'bound decrease', true means no active nodes are above bound b.
568 int k=n-2; //bound on the highest level under n containing a node
569 int b=k; //bound on the highest level under n of an active node
573 NNMap left(*g, INVALID);
574 NNMap right(*g, INVALID);
575 VecNode level_list(n,INVALID);
576 //List of the nodes in level i<n, set to n.
579 for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
580 //setting each node to level n
585 //counting the excess
587 for(g->first(v); g->valid(v); g->next(v)) {
591 for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
593 for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
597 //putting the active nodes into the stack
599 if ( exc > 0 && lev < n && v != t ) active[lev].push(v);
605 //Counting the excess of t
609 for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
611 for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
621 preflowPreproc( fe, active, level_list, left, right );
622 //End of preprocessing
625 //Push/relabel on the highest level active nodes.
628 if ( !what_heur && !end && k > 0 ) {
634 if ( active[b].empty() ) --b;
637 Node w=active[b].top();
639 int newlevel=push(w,active);
640 if ( excess[w] > 0 ) relabel(w, newlevel, active, level_list,
641 left, right, b, k, what_heur);
644 if ( numrelabel >= heur ) {
662 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
663 void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase1()
666 int k=n-2; //bound on the highest level under n containing a node
667 int b=k; //bound on the highest level under n of an active node
671 std::queue<Node> bfs_queue;
674 while (!bfs_queue.empty()) {
676 Node v=bfs_queue.front();
681 for(g->first(e,v); g->valid(e); g->next(e)) {
682 if ( (*capacity)[e] <= (*flow)[e] ) continue;
684 if ( level[u] >= n ) {
687 if ( excess[u] > 0 ) active[l].push(u);
692 for(g->first(f,v); g->valid(f); g->next(f)) {
693 if ( 0 >= (*flow)[f] ) continue;
695 if ( level[u] >= n ) {
698 if ( excess[u] > 0 ) active[l].push(u);
708 if ( active[b].empty() ) --b;
710 Node w=active[b].top();
712 int newlevel=push(w,active);
715 if ( excess[w] > 0 ) {
716 level.set(w,++newlevel);
717 active[newlevel].push(w);
720 } // if stack[b] is nonempty
726 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
727 bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnShortestPath()
729 ResGW res_graph(*g, *capacity, *flow);
732 //ReachedMap level(res_graph);
733 FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
734 BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
735 bfs.pushAndSetReached(s);
737 typename ResGW::template NodeMap<ResGWEdge> pred(res_graph);
738 pred.set(s, INVALID);
740 typename ResGW::template NodeMap<Num> free(res_graph);
742 //searching for augmenting path
743 while ( !bfs.finished() ) {
744 ResGWOutEdgeIt e=bfs;
745 if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
746 Node v=res_graph.tail(e);
747 Node w=res_graph.head(e);
749 if (res_graph.valid(pred[v])) {
750 free.set(w, std::min(free[v], res_graph.resCap(e)));
752 free.set(w, res_graph.resCap(e));
754 if (res_graph.head(e)==t) { _augment=true; break; }
758 } //end of searching augmenting path
762 Num augment_value=free[t];
763 while (res_graph.valid(pred[n])) {
765 res_graph.augment(e, augment_value);
781 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
782 template<typename MutableGraph>
783 bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow()
785 typedef MutableGraph MG;
788 ResGW res_graph(*g, *capacity, *flow);
790 //bfs for distances on the residual graph
791 //ReachedMap level(res_graph);
792 FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
793 BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
794 bfs.pushAndSetReached(s);
795 typename ResGW::template NodeMap<int>
796 dist(res_graph); //filled up with 0's
798 //F will contain the physical copy of the residual graph
799 //with the set of edges which are on shortest paths
801 typename ResGW::template NodeMap<typename MG::Node>
802 res_graph_to_F(res_graph);
804 typename ResGW::NodeIt n;
805 for(res_graph.first(n); res_graph.valid(n); res_graph.next(n)) {
806 res_graph_to_F.set(n, F.addNode());
810 typename MG::Node sF=res_graph_to_F[s];
811 typename MG::Node tF=res_graph_to_F[t];
812 typename MG::template EdgeMap<ResGWEdge> original_edge(F);
813 typename MG::template EdgeMap<Num> residual_capacity(F);
815 while ( !bfs.finished() ) {
816 ResGWOutEdgeIt e=bfs;
817 if (res_graph.valid(e)) {
818 if (bfs.isBNodeNewlyReached()) {
819 dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
820 typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)], res_graph_to_F[res_graph.head(e)]);
821 original_edge.update();
822 original_edge.set(f, e);
823 residual_capacity.update();
824 residual_capacity.set(f, res_graph.resCap(e));
826 if (dist[res_graph.head(e)]==(dist[res_graph.tail(e)]+1)) {
827 typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)], res_graph_to_F[res_graph.head(e)]);
828 original_edge.update();
829 original_edge.set(f, e);
830 residual_capacity.update();
831 residual_capacity.set(f, res_graph.resCap(e));
836 } //computing distances from s in the residual graph
842 //computing blocking flow with dfs
843 DfsIterator< MG, typename MG::template NodeMap<bool> > dfs(F);
844 typename MG::template NodeMap<typename MG::Edge> pred(F);
845 pred.set(sF, INVALID);
846 //invalid iterators for sources
848 typename MG::template NodeMap<Num> free(F);
850 dfs.pushAndSetReached(sF);
851 while (!dfs.finished()) {
853 if (F.valid(/*typename MG::OutEdgeIt*/(dfs))) {
854 if (dfs.isBNodeNewlyReached()) {
855 typename MG::Node v=F.aNode(dfs);
856 typename MG::Node w=F.bNode(dfs);
858 if (F.valid(pred[v])) {
859 free.set(w, std::min(free[v], residual_capacity[dfs]));
861 free.set(w, residual_capacity[dfs]);
870 F.erase(/*typename MG::OutEdgeIt*/(dfs));
876 typename MG::Node n=tF;
877 Num augment_value=free[tF];
878 while (F.valid(pred[n])) {
879 typename MG::Edge e=pred[n];
880 res_graph.augment(original_edge[e], augment_value);
882 if (residual_capacity[e]==augment_value)
885 residual_capacity.set(e, residual_capacity[e]-augment_value);
899 template <typename Graph, typename Num, typename CapMap, typename FlowMap>
900 bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow2()
904 ResGW res_graph(*g, *capacity, *flow);
906 //ReachedMap level(res_graph);
907 FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
908 BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
910 bfs.pushAndSetReached(s);
911 DistanceMap<ResGW> dist(res_graph);
912 while ( !bfs.finished() ) {
913 ResGWOutEdgeIt e=bfs;
914 if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
915 dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
918 } //computing distances from s in the residual graph
920 //Subgraph containing the edges on some shortest paths
921 ConstMap<typename ResGW::Node, bool> true_map(true);
922 typedef SubGraphWrapper<ResGW, ConstMap<typename ResGW::Node, bool>,
923 DistanceMap<ResGW> > FilterResGW;
924 FilterResGW filter_res_graph(res_graph, true_map, dist);
926 //Subgraph, which is able to delete edges which are already
928 typename FilterResGW::template NodeMap<typename FilterResGW::OutEdgeIt>
929 first_out_edges(filter_res_graph);
930 typename FilterResGW::NodeIt v;
931 for(filter_res_graph.first(v); filter_res_graph.valid(v);
932 filter_res_graph.next(v))
934 typename FilterResGW::OutEdgeIt e;
935 filter_res_graph.first(e, v);
936 first_out_edges.set(v, e);
938 typedef ErasingFirstGraphWrapper<FilterResGW, typename FilterResGW::
939 template NodeMap<typename FilterResGW::OutEdgeIt> > ErasingResGW;
940 ErasingResGW erasing_res_graph(filter_res_graph, first_out_edges);
947 //computing blocking flow with dfs
948 DfsIterator< ErasingResGW,
949 typename ErasingResGW::template NodeMap<bool> >
950 dfs(erasing_res_graph);
951 typename ErasingResGW::
952 template NodeMap<typename ErasingResGW::OutEdgeIt>
953 pred(erasing_res_graph);
954 pred.set(s, INVALID);
955 //invalid iterators for sources
957 typename ErasingResGW::template NodeMap<Num>
958 free1(erasing_res_graph);
960 dfs.pushAndSetReached(
961 typename ErasingResGW::Node(
962 typename FilterResGW::Node(
963 typename ResGW::Node(s)
967 while (!dfs.finished()) {
969 if (erasing_res_graph.valid(
970 typename ErasingResGW::OutEdgeIt(dfs)))
972 if (dfs.isBNodeNewlyReached()) {
974 typename ErasingResGW::Node v=erasing_res_graph.aNode(dfs);
975 typename ErasingResGW::Node w=erasing_res_graph.bNode(dfs);
977 pred.set(w, /*typename ErasingResGW::OutEdgeIt*/(dfs));
978 if (erasing_res_graph.valid(pred[v])) {
979 free1.set(w, std::min(free1[v], res_graph.resCap(
980 typename ErasingResGW::OutEdgeIt(dfs))));
982 free1.set(w, res_graph.resCap(
983 typename ErasingResGW::OutEdgeIt(dfs)));
992 erasing_res_graph.erase(dfs);
998 typename ErasingResGW::Node n=typename FilterResGW::Node(typename ResGW::Node(t));
999 // typename ResGW::NodeMap<Num> a(res_graph);
1000 // typename ResGW::Node b;
1002 // typename FilterResGW::NodeMap<Num> a1(filter_res_graph);
1003 // typename FilterResGW::Node b1;
1005 // typename ErasingResGW::NodeMap<Num> a2(erasing_res_graph);
1006 // typename ErasingResGW::Node b2;
1008 Num augment_value=free1[n];
1009 while (erasing_res_graph.valid(pred[n])) {
1010 typename ErasingResGW::OutEdgeIt e=pred[n];
1011 res_graph.augment(e, augment_value);
1012 n=erasing_res_graph.tail(e);
1013 if (res_graph.resCap(e)==0)
1014 erasing_res_graph.erase(e);
1018 } //while (__augment)
1028 #endif //HUGO_MAX_FLOW_H