/* -*- C++ -*- * demo/lp_maxflow_demo.cc - Part of LEMON, a generic C++ optimization library * * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport * (Egervary Research Group on Combinatorial Optimization, EGRES). * * Permission to use, modify and distribute this software is granted * provided that this copyright notice appears in all copies. For * precise terms see the accompanying LICENSE file. * * This software is provided "AS IS" with no warranty of any kind, * express or implied, and with no claim as to its suitability for any * purpose. * */ ///\ingroup demos ///\file ///\brief Max flow problem solved with an LP solver (demo). /// ///This demo program shows how to solve a maximum (or maximal) flow ///problem using the LEMON LP solver interface. We would like to lay ///the emphasis on the simplicity of the way one can formulate the LP ///constraints with LEMON that arise in graph theory. #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #ifdef HAVE_GLPK #include #elif HAVE_CPLEX #include #endif using namespace lemon; #ifdef HAVE_GLPK typedef LpGlpk LpDefault; const char default_solver_name[]="GLPK"; #elif HAVE_CPLEX typedef LpCplex LpDefault; const char default_solver_name[]="CPLEX"; #endif template double maxFlow(const G &g,const C &cap,typename G::Node s,typename G::Node t) { LpDefault lp; typedef G Graph; typedef typename G::Node Node; typedef typename G::NodeIt NodeIt; typedef typename G::Edge Edge; typedef typename G::EdgeIt EdgeIt; typedef typename G::OutEdgeIt OutEdgeIt; typedef typename G::InEdgeIt InEdgeIt; //Define a map on the edges for the variables of the LP problem typename G::template EdgeMap x(g); lp.addColSet(x); //Nonnegativity and capacity constraints for(EdgeIt e(g);e!=INVALID;++e) { lp.colUpperBound(x[e],cap[e]); lp.colLowerBound(x[e],0); } //Flow conservation constraints for the nodes (except for 's' and 't') for(NodeIt n(g);n!=INVALID;++n) if(n!=s&&n!=t) { LpDefault::Expr ex; for(InEdgeIt e(g,n);e!=INVALID;++e) ex+=x[e]; for(OutEdgeIt e(g,n);e!=INVALID;++e) ex-=x[e]; lp.addRow(ex==0); } //Objective function: the flow value entering 't' LpDefault::Expr obj; for(InEdgeIt e(g,t);e!=INVALID;++e) obj+=x[e]; for(OutEdgeIt e(g,t);e!=INVALID;++e) obj-=x[e]; lp.setObj(obj); //Maximization lp.max(); #ifdef HAVE_GLPK lp.presolver(true); lp.messageLevel(3); #endif std::cout<<"Solver used: "< cap(g); GraphReader reader(is,g); reader.readNode("source",s).readNode("target",t) .readEdgeMap("capacity",cap).run(); std::cout << "Max flow value = " << maxFlow(g,cap,s,t) << std::endl; }