2 #ifndef HUGO_MAX_FLOW_NO_STACK_H
 
     3 #define HUGO_MAX_FLOW_NO_STACK_H
 
     9 #include <hugo/graph_wrapper.h>
 
    10 #include <hugo/invalid.h>
 
    11 #include <hugo/maps.h>
 
    14 /// \brief The same as max_flow.h, but without using stl stack for the active nodes. Only for test.
 
    21   ///Maximum flow algorithms class.
 
    23   ///This class provides various algorithms for finding a flow of
 
    24   ///maximum value in a directed graph. The \e source node, the \e
 
    25   ///target node, the \e capacity of the edges and the \e starting \e
 
    26   ///flow value of the edges should be passed to the algorithm through the
 
    27   ///constructor. It is possible to change these quantities using the
 
    28   ///functions \ref resetSource, \ref resetTarget, \ref resetCap and
 
    29   ///\ref resetFlow. Before any subsequent runs of any algorithm of
 
    30   ///the class \ref resetFlow should be called. 
 
    32   ///After running an algorithm of the class, the actual flow value 
 
    33   ///can be obtained by calling \ref flowValue(). The minimum
 
    34   ///value cut can be written into a \c node map of \c bools by
 
    35   ///calling \ref minCut. (\ref minMinCut and \ref maxMinCut writes
 
    36   ///the inclusionwise minimum and maximum of the minimum value
 
    38   ///\param Graph The directed graph type the algorithm runs on.
 
    39   ///\param Num The number type of the capacities and the flow values.
 
    40   ///\param CapMap The capacity map type.
 
    41   ///\param FlowMap The flow map type.                                                                                                           
 
    42   ///\author Marton Makai, Jacint Szabo 
 
    43   template <typename Graph, typename Num,
 
    44 	    typename CapMap=typename Graph::template EdgeMap<Num>,
 
    45             typename FlowMap=typename Graph::template EdgeMap<Num> >
 
    48     typedef typename Graph::Node Node;
 
    49     typedef typename Graph::NodeIt NodeIt;
 
    50     typedef typename Graph::EdgeIt EdgeIt;
 
    51     typedef typename Graph::OutEdgeIt OutEdgeIt;
 
    52     typedef typename Graph::InEdgeIt InEdgeIt;
 
    54     //    typedef typename std::vector<std::stack<Node> > VecStack;
 
    55     typedef typename std::vector<Node> VecFirst;
 
    56     typedef typename Graph::template NodeMap<Node> NNMap;
 
    57     typedef typename std::vector<Node> VecNode;
 
    62     const CapMap* capacity;
 
    64     int n;      //the number of nodes of G
 
    65     typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;   
 
    66     //typedef ExpResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
 
    67     typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
 
    68     typedef typename ResGW::Edge ResGWEdge;
 
    69     //typedef typename ResGW::template NodeMap<bool> ReachedMap;
 
    70     typedef typename Graph::template NodeMap<int> ReachedMap;
 
    73     //level works as a bool map in augmenting path algorithms and is
 
    74     //used by bfs for storing reached information.  In preflow, it
 
    75     //shows the levels of nodes.     
 
    78     //excess is needed only in preflow
 
    79     typename Graph::template NodeMap<Num> excess;
 
    81     // constants used for heuristics
 
    82     static const int H0=20;
 
    83     static const int H1=1;
 
    87     ///Indicates the property of the starting flow.
 
    89     ///Indicates the property of the starting flow. The meanings are as follows:
 
    90     ///- \c ZERO_FLOW: constant zero flow
 
    91     ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
 
    92     ///the sum of the out-flows in every node except the \e source and
 
    94     ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at 
 
    95     ///least the sum of the out-flows in every node except the \e source.
 
    96     ///- \c NO_FLOW: indicates an unspecified edge map. \ref flow will be 
 
    97     ///set to the constant zero flow in the beginning of the algorithm in this case.
 
   108       AFTER_FAST_AUGMENTING, 
 
   109       AFTER_PRE_FLOW_PHASE_1,      
 
   110       AFTER_PRE_FLOW_PHASE_2
 
   113     /// Don not needle this flag only if necessary.
 
   116 //     int number_of_augmentations;
 
   119 //     template<typename IntMap>
 
   120 //     class TrickyReachedMap {
 
   123 //       int* number_of_augmentations;
 
   125 //       TrickyReachedMap(IntMap& _map, int& _number_of_augmentations) : 
 
   126 // 	map(&_map), number_of_augmentations(&_number_of_augmentations) { }
 
   127 //       void set(const Node& n, bool b) {
 
   129 // 	  map->set(n, *number_of_augmentations);
 
   131 // 	  map->set(n, *number_of_augmentations-1);
 
   133 //       bool operator[](const Node& n) const { 
 
   134 // 	return (*map)[n]==*number_of_augmentations; 
 
   140     ///\todo Document, please.
 
   142     MaxFlow(const Graph& _G, Node _s, Node _t,
 
   143 	    const CapMap& _capacity, FlowMap& _flow) :
 
   144       g(&_G), s(_s), t(_t), capacity(&_capacity),
 
   145       flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0), 
 
   146       status(AFTER_NOTHING) { }
 
   148     ///Runs a maximum flow algorithm.
 
   150     ///Runs a preflow algorithm, which is the fastest maximum flow
 
   151     ///algorithm up-to-date. The default for \c fe is ZERO_FLOW.
 
   152     ///\pre The starting flow must be
 
   153     /// - a constant zero flow if \c fe is \c ZERO_FLOW,
 
   154     /// - an arbitary flow if \c fe is \c GEN_FLOW,
 
   155     /// - an arbitary preflow if \c fe is \c PRE_FLOW,
 
   156     /// - any map if \c fe is NO_FLOW.
 
   157     void run(FlowEnum fe=ZERO_FLOW) {
 
   162     ///Runs a preflow algorithm.  
 
   164     ///Runs a preflow algorithm. The preflow algorithms provide the
 
   165     ///fastest way to compute a maximum flow in a directed graph.
 
   166     ///\pre The starting flow must be
 
   167     /// - a constant zero flow if \c fe is \c ZERO_FLOW,
 
   168     /// - an arbitary flow if \c fe is \c GEN_FLOW,
 
   169     /// - an arbitary preflow if \c fe is \c PRE_FLOW,
 
   170     /// - any map if \c fe is NO_FLOW.
 
   172     ///\todo NO_FLOW should be the default flow.
 
   173     void preflow(FlowEnum fe) {
 
   180     //   list 'level_list' on the nodes on level i implemented by hand
 
   181     //   stack 'active' on the active nodes on level i                                                                                    
 
   182     //   runs heuristic 'highest label' for H1*n relabels
 
   183     //   runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
 
   184     //   Parameters H0 and H1 are initialized to 20 and 1.
 
   186     ///Runs the first phase of the preflow algorithm.
 
   188     ///The preflow algorithm consists of two phases, this method runs the
 
   189     ///first phase. After the first phase the maximum flow value and a
 
   190     ///minimum value cut can already be computed, though a maximum flow
 
   191     ///is net yet obtained. So after calling this method \ref flowValue
 
   192     ///and \ref actMinCut gives proper results.
 
   193     ///\warning: \ref minCut, \ref minMinCut and \ref maxMinCut do not
 
   194     ///give minimum value cuts unless calling \ref preflowPhase2.
 
   195     ///\pre The starting flow must be
 
   196     /// - a constant zero flow if \c fe is \c ZERO_FLOW,
 
   197     /// - an arbitary flow if \c fe is \c GEN_FLOW,
 
   198     /// - an arbitary preflow if \c fe is \c PRE_FLOW,
 
   199     /// - any map if \c fe is NO_FLOW.
 
   200     void preflowPhase1(FlowEnum fe)
 
   203       int heur0=(int)(H0*n);  //time while running 'bound decrease'
 
   204       int heur1=(int)(H1*n);  //time while running 'highest label'
 
   205       int heur=heur1;         //starting time interval (#of relabels)
 
   209       //It is 0 in case 'bound decrease' and 1 in case 'highest label'
 
   212       //Needed for 'bound decrease', true means no active nodes are above bound
 
   215       int k=n-2;  //bound on the highest level under n containing a node
 
   216       int b=k;    //bound on the highest level under n of an active node
 
   218       VecFirst first(n, INVALID);
 
   219       NNMap next(*g, INVALID); //maybe INVALID is not needed
 
   221       NNMap left(*g, INVALID);
 
   222       NNMap right(*g, INVALID);
 
   223       VecNode level_list(n,INVALID);
 
   224       //List of the nodes in level i<n, set to n.
 
   227       for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
 
   228       //setting each node to level n
 
   230       if ( fe == NO_FLOW ) {
 
   232 	for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
 
   235       switch (fe) { //computing the excess
 
   239 	  for(g->first(v); g->valid(v); g->next(v)) {
 
   243 	    for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
 
   245 	    for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
 
   249 	    //putting the active nodes into the stack
 
   251 	    if ( exc > 0 && lev < n && v != t ) 
 
   253 		next.set(v,first[lev]);
 
   262 	  for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
 
   266 	  for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
 
   268 	  for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
 
   276 	  for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
 
   281       preflowPreproc(fe, next, first, level_list, left, right);
 
   282       //End of preprocessing
 
   285       //Push/relabel on the highest level active nodes.
 
   288 	  if ( !what_heur && !end && k > 0 ) {
 
   294 	if ( !g->valid(first[b]) ) --b;
 
   299 	  int newlevel=push(w, next, first);
 
   300 	  if ( excess[w] > 0 ) relabel(w, newlevel, next, first, level_list,
 
   301 				       left, right, b, k, what_heur);
 
   304 	  if ( numrelabel >= heur ) {
 
   319       status=AFTER_PRE_FLOW_PHASE_1;
 
   323     ///Runs the second phase of the preflow algorithm.
 
   325     ///The preflow algorithm consists of two phases, this method runs
 
   326     ///the second phase. After calling \ref preflowPhase1 and then
 
   327     ///\ref preflowPhase2 the methods \ref flowValue, \ref minCut,
 
   328     ///\ref minMinCut and \ref maxMinCut give proper results.
 
   329     ///\pre \ref preflowPhase1 must be called before.
 
   333       int k=n-2;  //bound on the highest level under n containing a node
 
   334       int b=k;    //bound on the highest level under n of an active node
 
   337       VecFirst first(n, INVALID);
 
   338       NNMap next(*g, INVALID); //maybe INVALID is not needed
 
   340       std::queue<Node> bfs_queue;
 
   343       while (!bfs_queue.empty()) {
 
   345 	Node v=bfs_queue.front();
 
   350 	for(g->first(e,v); g->valid(e); g->next(e)) {
 
   351 	  if ( (*capacity)[e] <= (*flow)[e] ) continue;
 
   353 	  if ( level[u] >= n ) {
 
   356 	    if ( excess[u] > 0 ) {
 
   357 	      next.set(u,first[l]);
 
   364 	for(g->first(f,v); g->valid(f); g->next(f)) {
 
   365 	  if ( 0 >= (*flow)[f] ) continue;
 
   367 	  if ( level[u] >= n ) {
 
   370 	    if ( excess[u] > 0 ) {
 
   371 	      next.set(u,first[l]);
 
   383 	if ( !g->valid(first[b]) ) --b;
 
   388 	  int newlevel=push(w,next, first/*active*/);
 
   391 	  if ( excess[w] > 0 ) {
 
   392 	    level.set(w,++newlevel);
 
   393 	    next.set(w,first[newlevel]);
 
   397 	}  // if stack[b] is nonempty
 
   400       status=AFTER_PRE_FLOW_PHASE_2;
 
   404     /// Returns the maximum value of a flow.
 
   406     /// Returns the maximum value of a flow, by counting the 
 
   407     /// over-flow of the target node \ref t.
 
   408     /// It can be called already after running \ref preflowPhase1.
 
   409     Num flowValue() const {
 
   411       for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
 
   412       for(OutEdgeIt e(*g,t);g->valid(e);g->next(e)) a-=(*flow)[e];
 
   414       //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan   
 
   416     Num flowValue2() const {
 
   419 //       for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
 
   420 //       for(OutEdgeIt e(*g,t);g->valid(e);g->next(e)) a-=(*flow)[e];
 
   422 //       //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan  
 
   426     ///Returns a minimum value cut after calling \ref preflowPhase1.
 
   428     ///After the first phase of the preflow algorithm the maximum flow
 
   429     ///value and a minimum value cut can already be computed. This
 
   430     ///method can be called after running \ref preflowPhase1 for
 
   431     ///obtaining a minimum value cut.
 
   432     /// \warning Gives proper result only right after calling \ref
 
   434     /// \todo We have to make some status variable which shows the
 
   436     /// of the class. This enables us to determine which methods are valid
 
   437     /// for MinCut computation
 
   438     template<typename _CutMap>
 
   439     void actMinCut(_CutMap& M) const {
 
   442       case AFTER_PRE_FLOW_PHASE_1:
 
   443 	for(g->first(v); g->valid(v); g->next(v)) {
 
   451       case AFTER_PRE_FLOW_PHASE_2:
 
   453       case AFTER_AUGMENTING:
 
   454       case AFTER_FAST_AUGMENTING:
 
   460     ///Returns the inclusionwise minimum of the minimum value cuts.
 
   462     ///Sets \c M to the characteristic vector of the minimum value cut
 
   463     ///which is inclusionwise minimum. It is computed by processing
 
   464     ///a bfs from the source node \c s in the residual graph.
 
   465     ///\pre M should be a node map of bools initialized to false.
 
   466     ///\pre \c flow must be a maximum flow.
 
   467     template<typename _CutMap>
 
   468     void minMinCut(_CutMap& M) const {
 
   469       std::queue<Node> queue;
 
   474       while (!queue.empty()) {
 
   475         Node w=queue.front();
 
   479 	for(g->first(e,w) ; g->valid(e); g->next(e)) {
 
   481 	  if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
 
   488 	for(g->first(f,w) ; g->valid(f); g->next(f)) {
 
   490 	  if (!M[v] && (*flow)[f] > 0 ) {
 
   498     ///Returns the inclusionwise maximum of the minimum value cuts.
 
   500     ///Sets \c M to the characteristic vector of the minimum value cut
 
   501     ///which is inclusionwise maximum. It is computed by processing a
 
   502     ///backward bfs from the target node \c t in the residual graph.
 
   503     ///\pre M should be a node map of bools initialized to false.
 
   504     ///\pre \c flow must be a maximum flow. 
 
   505     template<typename _CutMap>
 
   506     void maxMinCut(_CutMap& M) const {
 
   509       for(g->first(v) ; g->valid(v); g->next(v)) {
 
   513       std::queue<Node> queue;
 
   518       while (!queue.empty()) {
 
   519         Node w=queue.front();
 
   523 	for(g->first(e,w) ; g->valid(e); g->next(e)) {
 
   525 	  if (M[v] && (*flow)[e] < (*capacity)[e] ) {
 
   532 	for(g->first(f,w) ; g->valid(f); g->next(f)) {
 
   534 	  if (M[v] && (*flow)[f] > 0 ) {
 
   542     ///Returns a minimum value cut.
 
   544     ///Sets \c M to the characteristic vector of a minimum value cut.
 
   545     ///\pre M should be a node map of bools initialized to false.
 
   546     ///\pre \c flow must be a maximum flow.    
 
   547     template<typename CutMap>
 
   548     void minCut(CutMap& M) const { minMinCut(M); }
 
   550     ///Resets the source node to \c _s.
 
   552     ///Resets the source node to \c _s.
 
   554     void resetSource(Node _s) { s=_s; status=AFTER_NOTHING; }
 
   556     ///Resets the target node to \c _t.
 
   558     ///Resets the target node to \c _t.
 
   560     void resetTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
 
   562     /// Resets the edge map of the capacities to _cap.
 
   564     /// Resets the edge map of the capacities to _cap.
 
   566     void resetCap(const CapMap& _cap)
 
   567     { capacity=&_cap; status=AFTER_NOTHING; }
 
   569     /// Resets the edge map of the flows to _flow.
 
   571     /// Resets the edge map of the flows to _flow.
 
   573     void resetFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
 
   578     int push(Node w, NNMap& next, VecFirst& first) {
 
   582       int newlevel=n;       //bound on the next level of w
 
   585       for(g->first(e,w); g->valid(e); g->next(e)) {
 
   587 	if ( (*flow)[e] >= (*capacity)[e] ) continue;
 
   590 	if( lev > level[v] ) { //Push is allowed now
 
   592 	  if ( excess[v]<=0 && v!=t && v!=s ) {
 
   593 	    next.set(v,first[level[v]]);
 
   597 	  Num cap=(*capacity)[e];
 
   601 	  if ( remcap >= exc ) { //A nonsaturating push.
 
   603 	    flow->set(e, flo+exc);
 
   604 	    excess.set(v, excess[v]+exc);
 
   608 	  } else { //A saturating push.
 
   610 	    excess.set(v, excess[v]+remcap);
 
   613 	} else if ( newlevel > level[v] ) newlevel = level[v];
 
   618 	for(g->first(e,w); g->valid(e); g->next(e)) {
 
   620 	  if( (*flow)[e] <= 0 ) continue;
 
   623 	  if( lev > level[v] ) { //Push is allowed now
 
   625 	    if ( excess[v]<=0 && v!=t && v!=s ) {
 
   626 	      next.set(v,first[level[v]]);
 
   632 	    if ( flo >= exc ) { //A nonsaturating push.
 
   634 	      flow->set(e, flo-exc);
 
   635 	      excess.set(v, excess[v]+exc);
 
   638 	    } else {  //A saturating push.
 
   640 	      excess.set(v, excess[v]+flo);
 
   644 	  } else if ( newlevel > level[v] ) newlevel = level[v];
 
   647       } // if w still has excess after the out edge for cycle
 
   655     void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
 
   656 			VecNode& level_list, NNMap& left, NNMap& right)
 
   658       std::queue<Node> bfs_queue;
 
   661       case NO_FLOW:   //flow is already set to const zero in this case
 
   664 	  //Reverse_bfs from t, to find the starting level.
 
   668 	  while (!bfs_queue.empty()) {
 
   670 	    Node v=bfs_queue.front();
 
   675 	    for(g->first(e,v); g->valid(e); g->next(e)) {
 
   677 	      if ( level[w] == n && w != s ) {
 
   679 		Node z=level_list[l];
 
   680 		if ( g->valid(z) ) left.set(z,w);
 
   690 	  for(g->first(e,s); g->valid(e); g->next(e))
 
   692 	      Num c=(*capacity)[e];
 
   693 	      if ( c <= 0 ) continue;
 
   695 	      if ( level[w] < n ) {
 
   696 		if ( excess[w] <= 0 && w!=t ) 
 
   698 		    next.set(w,first[level[w]]);
 
   702 		excess.set(w, excess[w]+c);
 
   711 	  //Reverse_bfs from t in the residual graph,
 
   712 	  //to find the starting level.
 
   716 	  while (!bfs_queue.empty()) {
 
   718 	    Node v=bfs_queue.front();
 
   723 	    for(g->first(e,v); g->valid(e); g->next(e)) {
 
   724 	      if ( (*capacity)[e] <= (*flow)[e] ) continue;
 
   726 	      if ( level[w] == n && w != s ) {
 
   728 		Node z=level_list[l];
 
   729 		if ( g->valid(z) ) left.set(z,w);
 
   737 	    for(g->first(f,v); g->valid(f); g->next(f)) {
 
   738 	      if ( 0 >= (*flow)[f] ) continue;
 
   740 	      if ( level[w] == n && w != s ) {
 
   742 		Node z=level_list[l];
 
   743 		if ( g->valid(z) ) left.set(z,w);
 
   754 	  for(g->first(e,s); g->valid(e); g->next(e))
 
   756 	      Num rem=(*capacity)[e]-(*flow)[e];
 
   757 	      if ( rem <= 0 ) continue;
 
   759 	      if ( level[w] < n ) {
 
   760 		if ( excess[w] <= 0 && w!=t )
 
   762 		    next.set(w,first[level[w]]);
 
   765 		flow->set(e, (*capacity)[e]);
 
   766 		excess.set(w, excess[w]+rem);
 
   771 	  for(g->first(f,s); g->valid(f); g->next(f))
 
   773 	      if ( (*flow)[f] <= 0 ) continue;
 
   775 	      if ( level[w] < n ) {
 
   776 		if ( excess[w] <= 0 && w!=t )
 
   778 		    next.set(w,first[level[w]]);
 
   781 		excess.set(w, excess[w]+(*flow)[f]);
 
   792     void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
 
   793 		 VecNode& level_list, NNMap& left,
 
   794 		 NNMap& right, int& b, int& k, bool what_heur )
 
   799       Node right_n=right[w];
 
   803       if ( g->valid(right_n) ) {
 
   804 	if ( g->valid(left_n) ) {
 
   805 	  right.set(left_n, right_n);
 
   806 	  left.set(right_n, left_n);
 
   808 	  level_list[lev]=right_n;
 
   809 	  left.set(right_n, INVALID);
 
   812 	if ( g->valid(left_n) ) {
 
   813 	  right.set(left_n, INVALID);
 
   815 	  level_list[lev]=INVALID;
 
   820       if ( !g->valid(level_list[lev]) ) {
 
   823 	for (int i=lev; i!=k ; ) {
 
   824 	  Node v=level_list[++i];
 
   825 	  while ( g->valid(v) ) {
 
   829 	  level_list[i]=INVALID;
 
   830 	  if ( !what_heur ) first[i]=INVALID;
 
   840 	if ( newlevel == n ) level.set(w,n);
 
   842 	  level.set(w,++newlevel);
 
   843 	  next.set(w,first[newlevel]);
 
   845 	  if ( what_heur ) b=newlevel;
 
   846 	  if ( k < newlevel ) ++k;      //now k=newlevel
 
   847 	  Node z=level_list[newlevel];
 
   848 	  if ( g->valid(z) ) left.set(z,w);
 
   851 	  level_list[newlevel]=w;
 
   858 #endif //HUGO_MAX_FLOW_H