double f(double u, double v) { return abs(3*u + 4*v - 175); }
int
main(int argc,
char *argv[])
{
double *ptu = NULL;
double *ptz = NULL;
try {
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env);
// Create variables
double lb = 0, ub = 50;
GRBVar x = model.addVar(lb, ub, 0.0, GRB_INTEGER, "x");
GRBVar y = model.addVar(lb, ub, 0.0, GRB_INTEGER, "y");
GRBVar z = model.addVar(0, 25, 0.0, GRB_CONTINUOUS, "y");
// Add piecewise-linear objective functions
int npts = 101;
ptu = new double[npts];
ptz = new double[npts];
for (int i = 0; i < npts; i++) {
ptu[i] = lb + (ub - lb) * i / (npts - 1);
ptz[i] = f(ptu[i], ptu[i]);
}
model.setPWLObj(z, npts, ptu, ptz);
// Add constraint
model.addConstr(x + y == 50, "c0");
// Optimize model as an LP
model.optimize();
// Negate piecewise-linear objective function for x
for (int i = 0; i < npts; i++) {
ptz[i] = -ptz[i];
}
model.setPWLObj(z, npts, ptu, ptz);
// Optimize model as a MIP
model.optimize();
cout << "IsMIP: " << model.get(GRB_IntAttr_IsMIP) << endl;
cout << x.get(GRB_StringAttr_VarName) << " "
<< x.get(GRB_DoubleAttr_X) << endl;
cout << y.get(GRB_StringAttr_VarName) << " "
<< y.get(GRB_DoubleAttr_X) << endl;
cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
delete[] ptu;
delete[] ptz;
return 0;
}