开发者

lp_solve consecutive calls to `solve' are incorrect

I need to solve some simple linear integer programming-like problem, I took lp_solve library. The task is to obtain variables' values for some consequtive values of linear function with possible simple (linear) constraints on variables (actually I encountered a problem even without any additional constraints). E.g. I have linear function 4a + 5b. First values I'm interested in are (function value - variables values):

0 - (0, 0); 4 - (1, 0); 5 - (0, 1); 8 - (2, 0); 9 - (1, 1)

The problem is that after getting 8 - (2, 0), lp_solve returns NUMFAILURE code (5) while solving the task and resolves it to 0 - (0, 0)

If I do not use consequtive calls to 'solve' function and just start from 9 then I got right answer (9 - (1, 1)). Would anyone please explain this? The code is following.

#include <iostream>
#include <cstdio>

#include <lpsolve/lp_lib.h>

# if defined ERROR
#   undef ERROR
# endif
# define ERROR() { fprintf(stderr, "Error\n"); exit(1); }

using std::cout;
using std::endl;

void print_res(REAL * vars, int size) {
    cout << "(";
    for (int i = 0; i < size - 1; ++i) {
        cout << round(vars[i]) << ", ";
    }
    cout << round(vars[size - 1]) << ")";
}

int main()
{

    lprec *lp;
    int majorversion, minorversion, release, build, min = 0;

    lp_solve_version(&majorversion, &minorversion, &release, &build);


    const int l = 5;   // number of iterations
    const int dim = 2; // dimension ot current task
    char p_data[] = "4 5"; // objective function: p(a, b) = 4a + 5b


    if ((lp=make_lp(0,  dim)) == NULL)
        ERROR();
    set_verbose(lp, CRITICAL);

    if (!str_add_constraint(lp, p_data, GE, min)开发者_如何学C) // p(a, b) >= min
      ERROR();

    // objective function - p
    if (!str_set_obj_fn(lp, p_data))
      ERROR();

    // work with integer non-negative variables
    set_int(lp, 1, TRUE);
    set_int(lp, 2, TRUE);
    set_lowbo(lp, 1, 0);
    set_lowbo(lp, 2, 0);

    for (int i = 0; i < l; ++i) {
        cout <<  "Status: " << solve(lp) << endl;
        REAL vars[dim];
        get_variables(lp, vars);
        print_res(vars, dim);

        // increase minimum value for p
        min = round(get_objective(lp));
        cout << ", p = " << min << endl;

        if (!set_rh(lp, 1, min + 1))
          ERROR();
    }

    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜