gurobi.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "gurobi_c++.h"
  2. using namespace std;
  3. int
  4. main(int argc,
  5. char *argv[])
  6. {
  7. try {
  8. GRBEnv env = GRBEnv();
  9. GRBModel model = GRBModel(env);
  10. // Create variables
  11. GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "x");
  12. GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "y");
  13. GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "z");
  14. // Integrate new variables
  15. model.update();
  16. // Set objective: maximize x + y + 2 z
  17. model.setObjective(x + y + 2 * z, GRB_MAXIMIZE);
  18. // Add constraint: x + 2 y + 3 z <= 4
  19. model.addConstr(x + 2 * y + 3 * z <= 4, "c0");
  20. // Add constraint: x + y >= 1
  21. model.addConstr(x + y >= 1, "c1");
  22. // Optimize model
  23. model.optimize();
  24. cout << x.get(GRB_StringAttr_VarName) << " "
  25. << x.get(GRB_DoubleAttr_X) << endl;
  26. cout << y.get(GRB_StringAttr_VarName) << " "
  27. << y.get(GRB_DoubleAttr_X) << endl;
  28. cout << z.get(GRB_StringAttr_VarName) << " "
  29. << z.get(GRB_DoubleAttr_X) << endl;
  30. cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
  31. } catch(GRBException e) {
  32. cout << "Error code = " << e.getErrorCode() << endl;
  33. cout << e.getMessage() << endl;
  34. } catch(...) {
  35. cout << "Exception during optimization" << endl;
  36. }
  37. return 0;
  38. }