src/demo/lp_demo.cc
author alpar
Fri, 08 Apr 2005 06:34:34 +0000
changeset 1322 cfc26d103bcf
parent 1309 b3ce42a4d7d2
child 1326 85f1c483279e
permissions -rw-r--r--
Demo prog that computes the max flow by LP
     1 #include<lemon/lp_glpk.h>
     2 #include<lemon/graph_reader.h>
     3 #include<lemon/list_graph.h>
     4 
     5 using namespace lemon;
     6 
     7 template<class G,class C>
     8 double maxFlow(const G &g,const C &cap,typename G::Node s,typename G::Node t)
     9 {
    10   LpGlpk lp;
    11   
    12   typedef G Graph;
    13   typedef typename G::Node Node;
    14   typedef typename G::NodeIt NodeIt;
    15   typedef typename G::Edge Edge;
    16   typedef typename G::EdgeIt EdgeIt;
    17   typedef typename G::OutEdgeIt OutEdgeIt;
    18   typedef typename G::InEdgeIt InEdgeIt;
    19   
    20   typename G::template EdgeMap<LpGlpk::Col> x(g);
    21   lp.addColSet(x);
    22   
    23   for(EdgeIt e(g);e!=INVALID;++e) {
    24     lp.colUpperBound(x[e],cap[e]);
    25     lp.colLowerBound(x[e],0);
    26   }
    27 
    28   for(NodeIt n(g);n!=INVALID;++n) if(n!=s&&n!=t) {
    29     LpGlpk::Expr ex;
    30     for(InEdgeIt  e(g,n);e!=INVALID;++e) ex+=x[e];
    31     for(OutEdgeIt e(g,n);e!=INVALID;++e) ex-=x[e];
    32     lp.addRow(ex==0);
    33   }
    34   {
    35     LpGlpk::Expr ex;
    36     for(InEdgeIt  e(g,t);e!=INVALID;++e) ex+=x[e];
    37     for(OutEdgeIt e(g,t);e!=INVALID;++e) ex-=x[e];
    38     lp.setObj(ex);
    39   }
    40   lp.max();
    41   lp.solve();
    42 
    43   return lp.primalValue();
    44 }
    45 
    46 int main() 
    47 {
    48   LpGlpk lp_glpk;
    49 
    50   ListGraph g;
    51   ListGraph::Node s;
    52   ListGraph::Node t;
    53   
    54 
    55   ListGraph::EdgeMap<double> cap(g);
    56   
    57   GraphReader<ListGraph> reader(std::cin,g);
    58   reader.addNode("source",s).addNode("target",t)
    59     .addEdgeMap("capacity",cap).run();
    60   
    61   // std::ifstream file("../test/preflow_");
    62 //   readDimacs(file, g, cap, s, t);
    63 
    64   std::cout << "Max flow value = " << maxFlow(g,cap,s,t) << std::endl;
    65 
    66 }