mip2_c + + . cpp


/ * 2023年版权,Gurobi优狗万app足彩化,LLC * / / *这个例子从文件读取MIP模型,解决了它并打印客观值生成而解决MIP从所有可行的解决方案。然后它创建固定模型和解决模型。* / # include“gurobi_c + +。h”# include < cmath >使用名称空间性病;int主要(int命令行参数个数,char * argv[]){如果(命令行参数个数< 2){cout < <“用法:mip2_c + +文件名”< < endl;返回1;}GRBEnv * env = 0;GRBVar * fvars = 0;尝试{env = new GRBEnv ();GRBModel模型= GRBModel (* env, argv [1]); if (model.get(GRB_IntAttr_IsMIP) == 0) { throw GRBException("Model is not a MIP"); } model.optimize(); int optimstatus = model.get(GRB_IntAttr_Status); cout << "Optimization complete" << endl; double objval = 0; if (optimstatus == GRB_OPTIMAL) { objval = model.get(GRB_DoubleAttr_ObjVal); cout << "Optimal objective: " << objval << endl; } else if (optimstatus == GRB_INF_OR_UNBD) { cout << "Model is infeasible or unbounded" << endl; return 0; } else if (optimstatus == GRB_INFEASIBLE) { cout << "Model is infeasible" << endl; return 0; } else if (optimstatus == GRB_UNBOUNDED) { cout << "Model is unbounded" << endl; return 0; } else { cout << "Optimization was stopped with status = " << optimstatus << endl; return 0; } /* Iterate over the solutions and compute the objectives */ model.set(GRB_IntParam_OutputFlag, 0); cout << endl; for ( int k = 0; k < model.get(GRB_IntAttr_SolCount); ++k ) { model.set(GRB_IntParam_SolutionNumber, k); double objn = model.get(GRB_DoubleAttr_PoolObjVal); cout << "Solution " << k << " has objective: " << objn << endl; } cout << endl; model.set(GRB_IntParam_OutputFlag, 1); /* Create a fixed model, turn off presolve and solve */ GRBModel fixed = model.fixedModel(); fixed.set(GRB_IntParam_Presolve, 0); fixed.optimize(); int foptimstatus = fixed.get(GRB_IntAttr_Status); if (foptimstatus != GRB_OPTIMAL) { cerr << "Error: fixed model isn't optimal" << endl; return 0; } double fobjval = fixed.get(GRB_DoubleAttr_ObjVal); if (fabs(fobjval - objval) > 1.0e-6 * (1.0 + fabs(objval))) { cerr << "Error: objective values are different" << endl; return 0; } int numvars = model.get(GRB_IntAttr_NumVars); /* Print values of nonzero variables */ fvars = fixed.getVars(); for (int j = 0; j < numvars; j++) { GRBVar v = fvars[j]; if (v.get(GRB_DoubleAttr_X) != 0.0) { cout << v.get(GRB_StringAttr_VarName) << " " << v.get(GRB_DoubleAttr_X) << endl; } } } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch (...) { cout << "Error during optimization" << endl; } delete[] fvars; delete env; return 0; }