COIN-OR::LEMON - Graph Library

source: lemon-0.x/demo/lp_maxflow_demo.cc @ 1518:f8efed98d6a3

Last change on this file since 1518:f8efed98d6a3 was 1518:f8efed98d6a3, checked in by athos, 15 years ago

Only added comments.

File size: 2.0 KB
RevLine 
[1387]1#ifdef HAVE_CONFIG_H
2#include <config.h>
3#endif
4
[1361]5#include<lemon/graph_reader.h>
6#include<lemon/list_graph.h>
7
[1381]8
9#ifdef HAVE_GLPK
10#include <lemon/lp_glpk.h>
11#elif HAVE_CPLEX
12#include <lemon/lp_cplex.h>
13#endif
14
[1361]15using namespace lemon;
16
[1381]17#ifdef HAVE_GLPK
18typedef LpGlpk LpDefault;
19#elif HAVE_CPLEX
20typedef LpCplex LpDefault;
21#endif
22
23
[1361]24template<class G,class C>
25double maxFlow(const G &g,const C &cap,typename G::Node s,typename G::Node t)
26{
[1381]27  LpDefault lp;
[1361]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 
[1518]37  //Define a map on the edges for the variables of the LP problem
[1381]38  typename G::template EdgeMap<LpDefault::Col> x(g);
[1361]39  lp.addColSet(x);
40 
[1518]41  //Nonnegativity and capacity constraints
[1361]42  for(EdgeIt e(g);e!=INVALID;++e) {
43    lp.colUpperBound(x[e],cap[e]);
44    lp.colLowerBound(x[e],0);
45  }
46
[1518]47
48  //Flow conservation constraints for the nodes (except for 's' and 't')
[1361]49  for(NodeIt n(g);n!=INVALID;++n) if(n!=s&&n!=t) {
[1381]50    LpDefault::Expr ex;
[1361]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  }
[1518]55 
56  //Objective function: the flow value entering 't'
[1361]57  {
[1381]58    LpDefault::Expr ex;
[1361]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  }
[1518]63
64  //Maximization
[1361]65  lp.max();
66
[1381]67#ifdef HAVE_GLPK
[1361]68  lp.presolver(true);
69  lp.messageLevel(3);
[1381]70#endif
[1361]71
[1518]72  //Solve with the underlying solver
[1361]73  lp.solve();
74
75  return lp.primalValue();
76}
77
78int 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);
[1394]87  reader.readNode("source",s).readNode("target",t)
88    .readEdgeMap("capacity",cap).run();
[1361]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}
Note: See TracBrowser for help on using the repository browser.