使用C++调用Cplex(二)——增加约束求解LP问题
问题背景:这是个网络流模型 原始问题的模型为:
minimize c*x
subject to Hx = d
l <= x <= u
现在需要增加约束
AH=b
到原模型中,构成一个新的模型。
minimize c*x
subject to Hx = d (1)
Ax = b (2)
l <= x <= u
其中模型中各参数的数值为
H = ( 0 0 0 0 0 0 0 -1 -1 -1 0 0 ) d = ( -1 )
( 1 0 0 0 0 1 0 1 0 0 0 0 ) ( 4 )
( 0 1 0 1 0 0 1 0 1 0 0 0 ) ( 1 )
( 0 0 1 0 1 0 0 0 0 1 0 0 ) ( 1 )
( 0 0 0 0 0 -1 -1 0 0 0 -1 1 ) ( -2 )
( 0 0 0 -1 -1 0 1 0 0 0 1 0 ) ( -2 )
( -1 -1 -1 0 0 0 0 0 0 0 0 -1 ) ( -1 )
A = ( 0 0 0 0 0 0 0 0 0 0 2 5 ) b = ( 2 )
( 1 0 1 0 0 1 0 0 0 0 0 0 ) ( 3 )
c = ( 1 1 1 1 1 1 1 0 0 0 2 2 )
l = ( 0 0 0 0 0 0 0 0 0 0 0 0 )
u = ( 50 50 50 50 50 50 50 50 50 50 50 50 )
C++代码如下
#include <ilcplex/ilocplex.h>
ILOSTLBEGIN
int
main()
{
IloEnv env;
try {
IloModel model(env, "chvatal");
IloNumVarArray x(env, 12, 0.0, 50.0);
model.add(IloMinimize(env, x[0] + x[1] + x[2] + x[3] + x[4] +
x[5] + x[6] + 2*x[10] + 2*x[11] ));
model.add( -x[7]-x[8]-x[9]
== -1);
model.add( x[0] +x[5] +x[7]
== 4);
model.add( x[1] +x[3] +x[6] +x[8]
== 1);
model.add( x[2] +x[4] +x[9]
== 1);
model.add( -x[5]-x[6] -x[10]+x[11]
== -2);
model.add( -x[3]-x[4] +x[10]
== -2);
model.add(-x[0]-x[1]-x[2] -x[11]
== -1);
IloCplex cplex(model);
cplex.setParam(IloCplex::Param::Simplex::Display, 2);
cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Network);
cplex.solve();
cplex.out() << "After network optimization, objective is "
<< cplex.getObjValue() << endl;
model.add(2*x[10] + 5*x[11] == 2);
model.add( x[0] + x[2] + x[5] == 3);
cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Dual);
cplex.solve();
IloNumArray vals(env);
cplex.getValues(vals, x);
cplex.out() << "Solution status " << cplex.getStatus() << endl;
cplex.out() << "Objective value " << cplex.getObjValue() << endl;
cplex.out() << "Solution is: " << vals << endl;
cplex.exportModel("lpex3.lp");
}
catch (IloException& e) {
cerr << "Concert exception caught: " << e << endl;
}
catch (...) {
cerr << "Unknown exception caught" << endl;
}
env.end();
return 0;
```bash
代码运行结果如下: 求得[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11]=[0.6,0,0,1,1,2.4,0,1,0,0,0,0.4]
|