GLPK/条件约束
外观
	
	
< GLPK
有时,约束只有在满足可以用参数表达的条件时才有效。
以下不是合法的 GMPL
if (flag) {
    s.t. c : x <= 5;
} else {
    s.t. c : x <= 3;
}
但我们可以在 GMPL 中使用以下方式建模
/*
 * This model demonstrates how to let the existence of simple constraints
 * depend on a parameter.
 */
/* This flag controls if constraint c0 or contraint c1 is active */
param flag := 1;
var x;
maximize obj: x;
s.t. c0{i in {1} : flag == 0} : x <= 3;
s.t. c1{i in {1} : flag == 1} : x <= 5;
solve;
display x;
end;
对于索引条件,我们可以做同样的事情
/*
 * This model demonstrates how to let the existence of indexed constraints
 * depend on a parameter.
 */
/* This flag controls if constraint c0 or contraint c1 is active */
param flag := 0;
set I := {1..3};
var x{I}, <= 10; 
maximize obj: sum{i in I} x[i];
s.t. c0{i in I : i < 3 && flag == 0} : x[i] <= 3;
s.t. c1{i in I : i > 1 && flag == 1} : x[i] <= 5;
solve;
display x;
end;
如果约束的相关性取决于二元变量,我们可以使用 BigM 方法
/*
 * This model demonstrates how to let the relevance of indexed constraints
 * depend on a binary variable.
 */
/* Big M, chosen as small as possible */
param M := 7;
set I := {1..3};
var x{I}, <= 10; 
/* Binary variable controlling which constraint is active */
var y, binary;
maximize obj: sum{i in I} x[i];
s.t. c0{i in I : i < 2} : x[i] <= 3 + M * y;
s.t. c1{i in I : i > 1} : x[i] <= 5 + M * (1 - y); 
solve;
display x, y;
end;