教材——《get started with cplex》
求解一个简单的LP问题,问题描述如下
使用C++语言编写,代码如下:
#include<ilcplex/ilocplex.h>
ILOSTLBEGIN
int
main(int argc, char** argv) //argc 表示传入main函数的参数个数; argv 表示传入main函数的参数序列或者指针
{
IloEnv env;
try {
IloModel model(env);
IloNumVarArray vars(env);
vars.add(IloNumVar(env, 0.0, 40.0));
vars.add(IloNumVar(env));
vars.add(IloNumVar(env));
model.add(IloMaximize(env, vars[0] + 2 * vars[1] + 3 * vars[2]));
model.add(-vars[0] + vars[1] + vars[2] <= 20);
model.add( vars[0] - 3 * vars[1] + vars[2] <= 30);
IloCplex cplex(model);
if (!cplex.solve()) {
env.error() << "failed to optimize LP." << endl;
throw(-1);
}
IloNumArray vals(env);
env.out() << "Solution status=" << cplex.getStatus() << endl;
env.out() << "Solution value=" << cplex.getObjValue() << endl;
cplex.getValues(vals,vars);
env.out() << "Values=" << vals << endl;
}
catch (IloException& e) {
cerr << "Concert exception caught:" << e << endl;
}
catch (...) {
cerr << "Unknown exception caught" << endl;
}
env.end();
return 0;
}
运行结果图
求得 (x1,x2,x3)=(40,17.5,42.5)