线性规划中的glpk使用

做了卜东波老师的第四次线性规划的作业之后,对GLPK有了进一步的认识,作为一个线性规划的库,可以说实在是强大,但是说实话在开始编写相关代码的时候真的是很难,因为自己想要处理的问题的相关解决方法很少。但是最终还是写出来了。。可以说真的是很开心,感觉自己又拥有了一项技能。

首先是安装,可以在linux服务器上直接通过:sudo yum install glpk进行安装,安装的前提是拥有gcc,g++和python环境,这样才可以保证不出错。反正我在windows上面安装的时候由于没有vc就失败了,还真是linux服务器好用啊。

                                                                  Interval Scheduling Problem

A teaching building has m classrooms in total, and n courses are trying to use them. Each course i (i = 1, 2, · · · , n) only uses one classroom during time interval [Si, Fi) (Fi > Si > 0). Considering any two courses can not be carried on in a same classroom at any time, you have to select as many courses as possible and arrange them without any time collision. For simplicity, suppose 2n elements in the set {S1, F1, · · · , Sn, Fn} are all different.

Please use ILP to solve this problem, then construct an instance and use GLPK or Gurobi or other similar tools to solve it.

具体的意思是:

       表示教学楼一共有m个房间,对于n个课程来说怎么安排才可以使得最大限度的将课程安排在m个房间,使得安排的课程数量最多。其中对于课程i(i = 1,2,...,n)在时间间隔[Si,Fi)中仅使用一个教室(Fi> Si> 0)。考虑到任何时候都不能在同一个教室中进行任何两门课程,你必须选择尽可能多的课程,并安排它们没有任何时间碰撞。

根据这道题我们会得到不等式和相应的约束:

线性规划中的glpk使用_第1张图片

举例子:

设n = 5,m = 2

课程1,上课时间2:00-4:00

课程2,上课时间2:00-3:00

课程3,上课时间4:00-5:00

课程4,上课时间1:00-3:00

课程5,上课时间1:00-2:00

代码如下:

param n >= 0;
param m >= 0;
set NO_POINTS := 1..n;
set NO_SEGMENTS := 1..m;
param s{NO_POINTS};
param f{NO_POINTS};
var a{i in NO_POINTS,j in NO_SEGMENTS} binary;
var y_value;
s.t. cons1 {i in NO_POINTS} :
  1 >= sum{j in NO_SEGMENTS} a[i,j];
s.t. cons2 {j in NO_SEGMENTS, i in NO_POINTS, k in 1..i-1,i+1..n}:
  f[i]*(a[i,j] + a[k,j] - 1) <= s[k];
s.t. y_constraint :
  y_value = sum{j in NO_POINTS} sum {i in NO_SEGMENTS} a[j,i];
maximize total : y_value;
solve;
printf "y value = %10.2f\n\n", y_value;
printf "\n\n";
data;
param n := 5;
param m := 3;
param : s f :=
  1 2 4
  2 2 3
  3 4 5
  4 1 2
  5 1 3
;
end;

运行结果是: 

Scaling...
A: min|aij| = 1.000e+00 max|aij| = 1.000e+00 ratio = 1.000e+00
Problem data seem to be well scaled
Constructing initial basis...
Size of triangular part is 26
Solving LP relaxation...
GLPK Simplex Optimizer, v4.64
26 rows, 15 columns, 57 non-zeros
* 0: obj = -0.000000000e+00 inf = 0.000e+00 (15)
* 13: obj = 5.000000000e+00 inf = 0.000e+00 (0)
OPTIMAL LP SOLUTION FOUND
Integer optimization begins...
+ 13: mip = not found yet <= +inf (1; 0)
+ 13: »»> 5.000000000e+00 <= 5.000000000e+00 0.0% (1; 0)
+ 13: mip = 5.000000000e+00 <= tree is empty 0.0% (0; 1)
INTEGER OPTIMAL SOLUTION FOUND
Time used: 0.0 secs
Memory used: 0.2 Mb (157867 bytes)
y value = 5.00

你可能感兴趣的:(算法,线性规划)