问题
I'm trying to formulate that the variables x,y,z must all be different and that they accept only the values 1, 2 or 3 (this is, of course, a toy example):
min: x+y+z;
1 <= x <= 3;
1 <= y <= 3;
1 <= z <= 3;
but to make this work I still need either access to boolean operators or to a != operator, which don't seem to exist in lpsolve! How can I go about this? I wanted to do this:
x != y;
x != z;
y != z;
Thanks
EDIT:
Here's my current code:
/* Objective function */
min: 1;
/* Variable bounds */
1 <= x1 <= 4;
1 <= x2 <= 4;
1 <= x3 <= 4;
1 <= x4 <= 4;
x1 + x2 + x3 + x4 = 10;
x1 < x2;
x2 < x3;
x3 < x4;
int x1;
int x2;
int x3;
int x4;
lpsolve is giving me as result:
x1 = 1
x2 = 3
x3 = 3
x4 = 3
which is wrong. Why?
回答1:
In general I would agree with Michael Laffargue that it is not possible to have something like a < b
for real a,b in lpSolve. But for integer expressions that is a bit different.
Maybe we can start with a more simplified problem.
Let us think of two integer variables x and y and a constant M such that
1 <= x <= M and 1<=y<=M
.
If x and y may not be equal then x>y or y>x. But as both are integers only one of the following inequalities hold
x+1 <= y
y+1 <= x
We can enforce that only one of the inequalities above holds by introducing a binary variable r such that for x,y, r the following inequalities hold both :
(i) x+1 <= y+ Mr
(ii) y+1 <= x+M-Mr
because if r=0
then (i) x+1 <=y
and (ii) is trivial, but if r=1
then (ii) y+1 <= x
and (i) is trivial.
When we now apply the solution from above to the problem of the OP, then we can build a linear program with inequalities (i) and (ii) for all pairs of variables from the OP's problem and M=4
:
/* Objective function */
min: 1;
/* Variable bounds */
1 <= x1 <= 4;
1 <= x2 <= 4;
1 <= x3 <= 4;
1 <= x4 <= 4;
r_12 <= 1;
r_13 <= 1;
r_14 <= 1;
r_23 <= 1;
r_24 <= 1;
r_34 <= 1;
/* This is done automatically because all x1,..,x4 are different
x1 + x2 + x3 + x4 = 10;
*/
/* Apply (i) and (ii) to all pairs of x1,..x4
(i) x+1 <= y + Mr
(ii) y+1 <= x + M-Mr
*/
x1 + 1 <= x2 + 4 r_12;
x2 + 1 <= x1 + 4 - 4 r_12;
x1 + 1 <= x3 + 4 r_13;
x3 + 1 <= x1 + 4 - 4 r_13;
x1 + 1 <= x4 + 4 r_14;
x4 + 1 <= x4 + 4 - 4 r_14;
x2 + 1 <= x3 + 4 r_23;
x3 + 1 <= x2 + 4 - 4 r_23;
x2 + 1 <= x4 + 4 r_24;
x4 + 1 <= x2 + 4 - 4 r_24;
x3 + 1 <= x4 + 4 r_34;
x4 + 1 <= x3 + 4 - 4 r_34;
/*
x1 < x2;
x2 < x3;
x3 < x4;
*/
int r_12;
int r_13;
int r_14;
int r_23;
int r_24;
int r_34;
int x1;
int x2;
int x3;
int x4;
Solving the MILP above renders a solution with all x1,..,x4
different:
x1=3
x2=1
x3=2
x4=4
来源:https://stackoverflow.com/questions/30569008/how-to-formulate-x-y-in-lpsolve