alpar@1
|
1 |
/* SPP, Shortest Path Problem */
|
alpar@1
|
2 |
|
alpar@1
|
3 |
/* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */
|
alpar@1
|
4 |
|
alpar@1
|
5 |
/* Given a directed graph G = (V,E), its edge lengths c(i,j) for all
|
alpar@1
|
6 |
(i,j) in E, and two nodes s, t in V, the Shortest Path Problem (SPP)
|
alpar@1
|
7 |
is to find a directed path from s to t whose length is minimal. */
|
alpar@1
|
8 |
|
alpar@1
|
9 |
param n, integer, > 0;
|
alpar@1
|
10 |
/* number of nodes */
|
alpar@1
|
11 |
|
alpar@1
|
12 |
set E, within {i in 1..n, j in 1..n};
|
alpar@1
|
13 |
/* set of edges */
|
alpar@1
|
14 |
|
alpar@1
|
15 |
param c{(i,j) in E};
|
alpar@1
|
16 |
/* c[i,j] is length of edge (i,j); note that edge lengths are allowed
|
alpar@1
|
17 |
to be of any sign (positive, negative, or zero) */
|
alpar@1
|
18 |
|
alpar@1
|
19 |
param s, in {1..n};
|
alpar@1
|
20 |
/* source node */
|
alpar@1
|
21 |
|
alpar@1
|
22 |
param t, in {1..n};
|
alpar@1
|
23 |
/* target node */
|
alpar@1
|
24 |
|
alpar@1
|
25 |
var x{(i,j) in E}, >= 0;
|
alpar@1
|
26 |
/* x[i,j] = 1 means that edge (i,j) belong to shortest path;
|
alpar@1
|
27 |
x[i,j] = 0 means that edge (i,j) does not belong to shortest path;
|
alpar@1
|
28 |
note that variables x[i,j] are binary, however, there is no need to
|
alpar@1
|
29 |
declare them so due to the totally unimodular constraint matrix */
|
alpar@1
|
30 |
|
alpar@1
|
31 |
s.t. r{i in 1..n}: sum{(j,i) in E} x[j,i] + (if i = s then 1) =
|
alpar@1
|
32 |
sum{(i,j) in E} x[i,j] + (if i = t then 1);
|
alpar@1
|
33 |
/* conservation conditions for unity flow from s to t; every feasible
|
alpar@1
|
34 |
solution is a path from s to t */
|
alpar@1
|
35 |
|
alpar@1
|
36 |
minimize Z: sum{(i,j) in E} c[i,j] * x[i,j];
|
alpar@1
|
37 |
/* objective function is the path length to be minimized */
|
alpar@1
|
38 |
|
alpar@1
|
39 |
data;
|
alpar@1
|
40 |
|
alpar@1
|
41 |
/* Optimal solution is 20 that corresponds to the following shortest
|
alpar@1
|
42 |
path: s = 1 -> 2 -> 4 -> 8 -> 6 = t */
|
alpar@1
|
43 |
|
alpar@1
|
44 |
param n := 8;
|
alpar@1
|
45 |
|
alpar@1
|
46 |
param s := 1;
|
alpar@1
|
47 |
|
alpar@1
|
48 |
param t := 6;
|
alpar@1
|
49 |
|
alpar@1
|
50 |
param : E : c :=
|
alpar@1
|
51 |
1 2 1
|
alpar@1
|
52 |
1 4 8
|
alpar@1
|
53 |
1 7 6
|
alpar@1
|
54 |
2 4 2
|
alpar@1
|
55 |
3 2 14
|
alpar@1
|
56 |
3 4 10
|
alpar@1
|
57 |
3 5 6
|
alpar@1
|
58 |
3 6 19
|
alpar@1
|
59 |
4 5 8
|
alpar@1
|
60 |
4 8 13
|
alpar@1
|
61 |
5 8 12
|
alpar@1
|
62 |
6 5 7
|
alpar@1
|
63 |
7 4 5
|
alpar@1
|
64 |
8 6 4
|
alpar@1
|
65 |
8 7 10;
|
alpar@1
|
66 |
|
alpar@1
|
67 |
end;
|