demo/lp_maxflow_demo.cc
author alpar
Tue, 12 Jul 2005 16:16:19 +0000
changeset 1547 dd57a540ff5f
parent 1435 8e85e6bbefdf
child 1560 01707a8a4ca6
permissions -rw-r--r--
Improve doc
     1 #ifdef HAVE_CONFIG_H
     2 #include <config.h>
     3 #endif
     4 
     5 #include<lemon/graph_reader.h>
     6 #include<lemon/list_graph.h>
     7 
     8 
     9 #ifdef HAVE_GLPK
    10 #include <lemon/lp_glpk.h>
    11 #elif HAVE_CPLEX
    12 #include <lemon/lp_cplex.h>
    13 #endif
    14 
    15 using namespace lemon;
    16 
    17 #ifdef HAVE_GLPK
    18 typedef LpGlpk LpDefault;
    19 #elif HAVE_CPLEX
    20 typedef LpCplex LpDefault;
    21 #endif
    22 
    23 
    24 template<class G,class C>
    25 double maxFlow(const G &g,const C &cap,typename G::Node s,typename G::Node t)
    26 {
    27   LpDefault lp;
    28   
    29   typedef G Graph;
    30   typedef typename G::Node Node;
    31   typedef typename G::NodeIt NodeIt;
    32   typedef typename G::Edge Edge;
    33   typedef typename G::EdgeIt EdgeIt;
    34   typedef typename G::OutEdgeIt OutEdgeIt;
    35   typedef typename G::InEdgeIt InEdgeIt;
    36   
    37   //Define a map on the edges for the variables of the LP problem
    38   typename G::template EdgeMap<LpDefault::Col> x(g);
    39   lp.addColSet(x);
    40   
    41   //Nonnegativity and capacity constraints
    42   for(EdgeIt e(g);e!=INVALID;++e) {
    43     lp.colUpperBound(x[e],cap[e]);
    44     lp.colLowerBound(x[e],0);
    45   }
    46 
    47 
    48   //Flow conservation constraints for the nodes (except for 's' and 't')
    49   for(NodeIt n(g);n!=INVALID;++n) if(n!=s&&n!=t) {
    50     LpDefault::Expr ex;
    51     for(InEdgeIt  e(g,n);e!=INVALID;++e) ex+=x[e];
    52     for(OutEdgeIt e(g,n);e!=INVALID;++e) ex-=x[e];
    53     lp.addRow(ex==0);
    54   }
    55   
    56   //Objective function: the flow value entering 't'
    57   {
    58     LpDefault::Expr ex;
    59     for(InEdgeIt  e(g,t);e!=INVALID;++e) ex+=x[e];
    60     for(OutEdgeIt e(g,t);e!=INVALID;++e) ex-=x[e];
    61     lp.setObj(ex);
    62   }
    63 
    64   //Maximization
    65   lp.max();
    66 
    67 #ifdef HAVE_GLPK
    68   lp.presolver(true);
    69   lp.messageLevel(3);
    70 #endif
    71 
    72   //Solve with the underlying solver
    73   lp.solve();
    74 
    75   return lp.primalValue();
    76 }
    77 
    78 int main() 
    79 {
    80   ListGraph g;
    81   ListGraph::Node s;
    82   ListGraph::Node t;
    83   
    84   ListGraph::EdgeMap<double> cap(g);
    85   
    86   GraphReader<ListGraph> reader(std::cin,g);
    87   reader.readNode("source",s).readNode("target",t)
    88     .readEdgeMap("capacity",cap).run();
    89   
    90   // std::ifstream file("../test/preflow_");
    91 //   readDimacs(file, g, cap, s, t);
    92 
    93   std::cout << "Max flow value = " << maxFlow(g,cap,s,t) << std::endl;
    94 
    95 }