Adding constraints to the model
Once the new variables are integrated into the model, the next step is to add our two linear constraints. These constraints are added through the GRBaddconstr() routine. To add a constraint, you must specify several pieces of information, including the non-zero values associated with the constraint, the constraint sense, the right-hand side value, and the constraint name. These are all specified as arguments to GRBaddconstr():
/* First constraint: x + 2 y + 3 z <= 4 */ ind[0] = 0; ind[1] = 1; ind[2] = 2; val[0] = 1; val[1] = 2; val[2] = 3; error = GRBaddconstr(model, 3, ind, val, GRB_LESS_EQUAL, 4.0, NULL); if (error) goto QUIT;The first argument of GRBaddconstr() is the model to which the constraint is being added. The second is the total number of non-zero coefficients associated with the new constraint. The next two arguments describe the non-zeros in the new constraint. Constraint coefficients are specified using a list of index-value pairs, one for each non-zero value. In our example, the first constraint to be added is




ind
and
val
arrays.
The fifth argument to GRBaddconstr() provides the sense of the
new constraint. Possible values are GRB_LESS_EQUAL
,
GRB_GREATER_EQUAL
, or GRB_EQUAL
. The sixth argument gives
the right-hand side value. The final argument gives the name of the
constraint (we allow the constraint to take its default name here by
specifying NULL
for the argument).
The second constraint is added in a similar fashion:
/* Second constraint: x + y >= 1 */ ind[0] = 0; ind[1] = 1; val[0] = 1; val[1] = 1; error = GRBaddconstr(model, 2, ind, val, GRB_GREATER_EQUAL, 1.0, NULL); if (error) goto QUIT;Note that routine GRBaddconstrs() would allow you to add both constraints in a single call. The arguments for this routine are much more complex, though, without providing any significant advantages, so we recommend that you add one constraint at a time.