java上的背包问题 - 输出总是目标函数

问题描述 投票:0回答:2

您好,我正在尝试使用java和cplex 12.8创建并解决只有1个bin的简单背包问题。我不明白为什么它总是在输出中给出目标函数的值。这是我的完整代码:

    public static void solveModel(){       

        try {

            n_obj = 5;
            int capacity = 4

            int[] profits = new int[n_obj];
            for(int i = 0; i < n_obj; i++ ){
                weight[i] = ThreadLocalRandom.current().nextInt(1, n_obj/2 + 1);
                profits[i] = ThreadLocalRandom.current().nextInt(1, 12);
            }


            for(int i = 0; i < weight.length; i++){
                System.out.println("Weight " + i + ":\t" + weight[i]);
                System.out.println("Profit " + i + ":\t" + profits[i]);

            }

            IloCplex model = new IloCplex();
            IloNumVar x = model.boolVar();



            IloLinearNumExpr obj = model.linearNumExpr();
            for(int i = 0; i < n_obj; i++){
                obj.addTerm(profits[i], x);
            }

            //obj function
            model.addMaximize(obj);

            //constraints

            for(int i = 0; i < n_obj; i++){
                model.addLe(model.prod(weight[i], x), capacity) ;
                model.addEq(x, 1);

            }

            if (model.solve()) {

                System.out.println("Obj = " + model.getObjValue());
            }
            else {
                System.out.println("Problem not solved");
            }

            model.end();



        } catch (IloException e) {
            e.printStackTrace();
        }

    }

我将n_obj和容量设置为固定值,以使其尽可能简单。每次输出都是这样的:

Weight 0:   1
Profit 0:   2
Weight 1:   1
Profit 1:   11
Weight 2:   2
Profit 2:   2
Weight 3:   1
Profit 3:   7
Weight 4:   2
Profit 4:   6
Found incumbent of value 28.000000 after 0.00 sec. (0.00 ticks)

Root node processing (before b&c):
Real time             =    0.00 sec. (0.00 ticks)
Parallel b&c, 8 threads:
  Real time             =    0.00 sec. (0.00 ticks)
  Sync time (average)   =    0.00 sec.
  Wait time (average)   =    0.00 sec.
                      ------------
Total (root+branch&cut) =    0.00 sec. (0.00 ticks)
Obj = 28.0
java cplex knapsack-problem
2个回答
1
投票

好吧,对于那些曾经或将要感兴趣的人......我自己解决了。布尔变量的声明以这种方式完成:

IloNumVar[] x = new IloNumVar[n_obj];
for (int i = 0; i < n_obj; i++) {
//x[i] = model.numVar(0, Double.POSITIVE_INFINITY, IloNumVarType.Bool, "x[" + i + 
//"]");
    x[i] = model.boolVar();
}

我修改了约束:

 IloLinearNumExpr lin = model.linearNumExpr();
        for (int i = 0; i < n_obj; i++) {
            //model.addLe(model.prod(weight[i], x[i]), capacity);
            lin.addTerm(x[i], weight[i]);
        }

        model.addLe(lin, capacity, "Constraints");

我知道这是一个简单的背包问题,但我是一个复杂的初学者,我希望它对其他人有用。

玩得开心


0
投票

CPLEX为您的问题计算出最佳解决方案,目标值为28。

默认情况下,CPLEX以完全确定的方式运行。也就是说,当在相同条件下运行多次(同样的问题需要解决,同一台机器等)时,CPLEX将始终返回完全相同的结果。因此,在多次运行程序时没有理由期待不同的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.