VS中C++语言调用gurobi求解器

1、创建空项目,并建立一个cpp

2、设置debug   x64

3、c/c++   常规   附加包含目录

F:\programmsoftware\Groubi\win64\include

4、链接器   常规  附加库目录

F:\programmsoftware\Groubi\win64\lib

5、链接器   输入  附加依赖项  gurobi110.lib   gurobi_c++mdd2017.lib   这个文件需要看自己的gurobi安装目录下lib里的数字

6、使用测试代码测试

/* Copyright 2023, Gurobi Optimization, LLC */

/* This example formulates and solves the following simple QP model:

     minimize    x^2 + x*y + y^2 + y*z + z^2 + 2 x
     subject to  x + 2 y + 3 z >= 4
                 x +   y       >= 1
                 x, y, z non-negative

   It solves it once as a continuous model, and once as an integer model.
*/

#include "gurobi_c++.h"
using namespace std;

int  main(int   argc, char* argv[])
{
    try {
        GRBEnv env = GRBEnv();

        GRBModel model = GRBModel(env);

        // Create variables

        GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "x");
        GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "y");
        GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "z");

        // Set objective

        GRBQuadExpr obj = x * x + x * y + y * y + y * z + z * z + 2 * x;
        model.setObjective(obj);

        // Add constraint: x + 2 y + 3 z >= 4

        model.addConstr(x + 2 * y + 3 * z >= 4, "c0");

        // Add constraint: x + y >= 1

        model.addConstr(x + y >= 1, "c1");

        // Optimize model

        model.optimize();

        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 << z.get(GRB_StringAttr_VarName) << " "
            << z.get(GRB_DoubleAttr_X) << endl;

        cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;

        // Change variable types to integer

        x.set(GRB_CharAttr_VType, GRB_INTEGER);
        y.set(GRB_CharAttr_VType, GRB_INTEGER);
        z.set(GRB_CharAttr_VType, GRB_INTEGER);

        // Optimize model

        model.optimize();

        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 << z.get(GRB_StringAttr_VarName) << " "
            << z.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;
    }

    return 0;
}

7、结果如下

Gurobi Optimizer version 11.0.0 build v11.0.0rc2 (win64 - Windows 11.0 (22621.2))

CPU model: 12th Gen Intel(R) Core(TM) i9-12900H, instruction set [SSE2|AVX|AVX2]
Thread count: 14 physical cores, 20 logical processors, using up to 20 threads

Optimize a model with 2 rows, 3 columns and 5 nonzeros
Model fingerprint: 0xc501370b
Model has 5 quadratic objective terms
Coefficient statistics:
  Matrix range     [1e+00, 3e+00]
  Objective range  [2e+00, 2e+00]
  QObjective range [2e+00, 2e+00]
  Bounds range     [1e+00, 1e+00]
  RHS range        [1e+00, 4e+00]
Presolve time: 0.00s
Presolved: 2 rows, 3 columns, 5 nonzeros
Presolved model has 5 quadratic objective terms
Ordering time: 0.00s

Barrier statistics:
 Free vars  : 2
 AA' NZ     : 6.000e+00
 Factor NZ  : 1.000e+01
 Factor Ops : 3.000e+01 (less than 1 second per iteration)
 Threads    : 1

                  Objective                Residual
Iter       Primal          Dual         Primal    Dual     Compl     Time
   0   1.69015022e+05 -1.71012100e+05  1.50e+03 3.33e+02  1.00e+06     0s
   1   3.60255402e+04 -3.91306233e+04  2.28e+02 3.82e+01  1.20e+05     0s
   2   4.14685168e+00 -4.40925173e+03  1.80e+00 4.00e-01  1.83e+03     0s
   3   2.81937163e+00 -1.92736174e+03  1.80e-06 4.00e-07  2.41e+02     0s
   4   2.81628339e+00 -1.81287557e-01  8.60e-10 1.91e-10  3.75e-01     0s
   5   2.26977145e+00  2.06670895e+00  6.89e-12 1.53e-12  2.54e-02     0s
   6   2.11498124e+00  2.11029644e+00  0.00e+00 2.22e-16  5.86e-04     0s
   7   2.11111498e+00  2.11111030e+00  0.00e+00 2.50e-16  5.85e-07     0s
   8   2.11111111e+00  2.11111111e+00  0.00e+00 4.62e-17  5.86e-10     0s

Barrier solved model in 8 iterations and 0.00 seconds (0.00 work units)
Optimal objective 2.11111111e+00

x 3.255e-09
y 1
z 0.666667
Obj: 2.11111
Gurobi Optimizer version 11.0.0 build v11.0.0rc2 (win64 - Windows 11.0 (22621.2))

CPU model: 12th Gen Intel(R) Core(TM) i9-12900H, instruction set [SSE2|AVX|AVX2]
Thread count: 14 physical cores, 20 logical processors, using up to 20 threads

Optimize a model with 2 rows, 3 columns and 5 nonzeros
Model fingerprint: 0x026954d2
Model has 5 quadratic objective terms
Variable types: 0 continuous, 3 integer (0 binary)
Coefficient statistics:
  Matrix range     [1e+00, 3e+00]
  Objective range  [2e+00, 2e+00]
  QObjective range [2e+00, 2e+00]
  Bounds range     [1e+00, 1e+00]
  RHS range        [1e+00, 4e+00]
Found heuristic solution: objective 7.0000000
Presolve removed 1 rows and 1 columns
Presolve time: 0.00s
Presolved: 2 rows, 3 columns, 5 nonzeros
Variable types: 0 continuous, 3 integer (3 binary)
Found heuristic solution: objective 3.0000000

Explored 0 nodes (0 simplex iterations) in 0.00 seconds (0.00 work units)
Thread count was 20 (of 20 available processors)

Solution count 2: 3 7

Optimal solution found (tolerance 1.00e-04)
Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0000%
x 0
y 1
z 1
Obj: 3

E:\vs_project博\gurobiTest\x64\Debug\gurobiTest.exe (进程 37404)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

TSP(Traveling Salesman Problem)是一个经典的 NP 难问题,暴力搜索解决不了,需要使用启发式算法或者求解求解是一种专门用于求解优化问题的软件,可以快速求解 TSP 问题。 下面是使用 C++ 调用求解 Gurobi 求解 TSP 问题的示例代码: ```cpp #include <iostream> #include <cstring> #include <gurobi_c++.h> // 引入 Gurobi 求解头文件 using namespace std; const int N = 20; int n; double x[N], y[N]; double dist[N][N]; int main() { cin >> n; for (int i = 0; i < n; i++) cin >> x[i] >> y[i]; // 计算距离矩阵 for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) dist[i][j] = dist[j][i] = sqrt((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j])); try { GRBEnv env = GRBEnv(); // 创建 Gurobi 环境 GRBModel model = GRBModel(env); // 创建 Gurobi 模型 model.set(GRB_StringAttr_ModelName, "tsp"); // 设置模型名称 // 创建决策变量 GRBVar x[n][n]; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) x[i][j] = model.addVar(0.0, 1.0, dist[i][j], GRB_CONTINUOUS, "x_" + to_string(i) + "_" + to_string(j)); // 添加约束条件 for (int i = 0; i < n; i++) { GRBLinExpr expr = 0; for (int j = 0; j < n; j++) { if (i == j) continue; expr += x[i][j]; } model.addConstr(expr == 2); } // 设置目标函数 GRBLinExpr obj = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) obj += x[i][j]; model.setObjective(obj, GRB_MINIMIZE); // 求解模型 model.optimize(); // 输出结果 cout << "Optimal tour: "; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (x[i][j].get(GRB_DoubleAttr_X) > 0.5) cout << i << " -> " << j << " "; cout << endl; cout << "Optimal distance: " << 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; } return 0; } ``` 上面的代码,我们使用 Gurobi 求解求解 TSP 问题。首先,我们需要引入 Gurobi 求解的头文件 `gurobi_c++.h`。然后,我们需要创建 Gurobi 环境和模型,设置模型名称。 接着,我们需要创建决策变量,即二维数组 `x[i][j]` 表示从节点 i 到节点 j 是否走这条边。我们需要设置决策变量的取值范围,即 0 到 1 之间的实数,并设置决策变量的系数,即边的长度。然后,我们需要添加约束条件,即每个节点都恰好走一次,并设置目标函数,即最小化总路程。 最后,我们调用模型的 `optimize` 方法来求解模型,输出最优解,即遍历所有节点的最短路径和总长度。如果求解过程出现错误,我们需要捕获异常并输出错误信息。 需要注意的是,在使用 Gurobi 求解时,我们需要先在官网上下载并安装 Gurobi 软件,并获取一个 Gurobi 许可证才能使用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值