src/demo/lp_maxflow_demo.cc
author marci
Sat, 23 Apr 2005 16:59:49 +0000
changeset 1383 79b68a337f9f
parent 1361 04733359bac2
child 1387 37d1b20cd9ef
permissions -rw-r--r--
A new implementation of UndirGraphWrapper, accordig to the undirected concepts
     1 #include<lemon/graph_reader.h>
     2 #include<lemon/list_graph.h>
     3 
     4 
     5 #ifdef HAVE_GLPK
     6 #include <lemon/lp_glpk.h>
     7 #elif HAVE_CPLEX
     8 #include <lemon/lp_cplex.h>
     9 #endif
    10 
    11 using namespace lemon;
    12 
    13 #ifdef HAVE_GLPK
    14 typedef LpGlpk LpDefault;
    15 #elif HAVE_CPLEX
    16 typedef LpCplex LpDefault;
    17 #endif
    18 
    19 
    20 template<class G,class C>
    21 double maxFlow(const G &g,const C &cap,typename G::Node s,typename G::Node t)
    22 {
    23   LpDefault lp;
    24   
    25   typedef G Graph;
    26   typedef typename G::Node Node;
    27   typedef typename G::NodeIt NodeIt;
    28   typedef typename G::Edge Edge;
    29   typedef typename G::EdgeIt EdgeIt;
    30   typedef typename G::OutEdgeIt OutEdgeIt;
    31   typedef typename G::InEdgeIt InEdgeIt;
    32   
    33   typename G::template EdgeMap<LpDefault::Col> x(g);
    34   lp.addColSet(x);
    35   
    36   for(EdgeIt e(g);e!=INVALID;++e) {
    37     lp.colUpperBound(x[e],cap[e]);
    38     lp.colLowerBound(x[e],0);
    39   }
    40 
    41   for(NodeIt n(g);n!=INVALID;++n) if(n!=s&&n!=t) {
    42     LpDefault::Expr ex;
    43     for(InEdgeIt  e(g,n);e!=INVALID;++e) ex+=x[e];
    44     for(OutEdgeIt e(g,n);e!=INVALID;++e) ex-=x[e];
    45     lp.addRow(ex==0);
    46   }
    47   {
    48     LpDefault::Expr ex;
    49     for(InEdgeIt  e(g,t);e!=INVALID;++e) ex+=x[e];
    50     for(OutEdgeIt e(g,t);e!=INVALID;++e) ex-=x[e];
    51     lp.setObj(ex);
    52   }
    53   lp.max();
    54 
    55 #ifdef HAVE_GLPK
    56   lp.presolver(true);
    57   lp.messageLevel(3);
    58 #endif
    59 
    60   lp.solve();
    61 
    62   return lp.primalValue();
    63 }
    64 
    65 int main() 
    66 {
    67   ListGraph g;
    68   ListGraph::Node s;
    69   ListGraph::Node t;
    70   
    71   ListGraph::EdgeMap<double> cap(g);
    72   
    73   GraphReader<ListGraph> reader(std::cin,g);
    74   reader.addNode("source",s).addNode("target",t)
    75     .addEdgeMap("capacity",cap).run();
    76   
    77   // std::ifstream file("../test/preflow_");
    78 //   readDimacs(file, g, cap, s, t);
    79 
    80   std::cout << "Max flow value = " << maxFlow(g,cap,s,t) << std::endl;
    81 
    82 }