1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
#+title: Interactive graph visualizer and laboratory suite
* Tasks
** Random DAG generation and shimbel path metrics[fn:1]
1. Generate a randomly connected acyclic graph according to a given
distribution (distribution parameters set as constants) with the
required number of vertices. The distribution is best taken from
the Wadzinski handbook.
2. Implement the Shimbell method on the resulting graph (the user
enters number of edges).
3. Determine the possibility of building a route from one specified
point to another one (the vertex is entered by the user) and find
the number of such routes.
** Shortest paths and algorithm performance comparison[fn:2]
1. For the given graphs (randomly generated in the previous task) it
is necessary to generate a weight matrix (positive or with negative
weights -- the user chooses) and find the shortest path for two
points selected by the user. The user enters the numbers of the
starting and ending vertices. As a result, not only the distance
is displayed, but also the path itself in the form of a sequence of
vertices. For Dijkstra’s and Bellman‑Ford’s algorithms, it is
necessary output the distance vector, for Floyd-Warshall -- the
matrix distances. Implemented algorithms:
- *classic Dijkstra algorithm*
- *the Floyd-Warshall algorithm*
- *Finding the maximum path* (for user-defined vertices)
2. Compare the speeds of these algorithms (by number of iterations).
** Maximum flow and minimum-cost network flows[fn:3]
1. Form a connected acyclic graph randomly in according to the
specified distribution. Based on it, build throughput and cost
matrices.
2. For the resulting graph, find the maximum flow using the algorithm
Ford-Fulkerson (or any of those listed in the lecture).
3. Calculate the minimum cost flow (as the flow value take a value
equal to ⅔max, where max is the maximum flow). Use previously
implemented Dijkstra and/or Bellman-Ford algorithms.
** Spanning trees, matrix-tree theorem, and Prüfer codes[fn:4]
1. For the given graphs (randomly generated in the first task), using
Kirchhoff’s matrix theorem, find the number of spanning trees in
the original graph.
2. Construct a minimum‑weight spanning tree for the generated weighted
graph using the *Prim* and *Boruvka* algorithms. Compare The given
algorithms (by the number of iterations).
3. Encode the resulting skeleton using the Prüfer code and decode it.
his. It is essential to maintain the weights during encoding.
** Eulerian, Hamiltonian, and traveling salesman problems[fn:5]
1. For the given graphs (randomly generated in the first task), check
whether the graph is Eulerian and Hamiltonian.
2. Check whether the graph is Eulerian. If not, modify the graph
(show what was changed). Construct an Eulerian cycle.
3. Check whether the graph is Hamiltonian. If not, modify the graph
(show what was changed). Solve the problem. The traveling
salesman problem on a Hamiltonian graph (we output all Hamiltonian
cycles with a total weight either to the screen if there are few of
them, or to a file). There are separate bonuses for implemented
heuristics (by default, a complete search).
* Documentation
The exported report can be found at [[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/report.pdf][this link]].
* Showcase
** Distribution of the random number generator
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/distribution-my.png]]
** Creation of graph with 8 vertices
#+attr_html: :width 800em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph1.png]]
#+begin_example
ADJECENCY_MATRIX:
[00][01][02][03][04][05][06][07]
[0] 0 0 0 0 0 1 0 0
[1] 0 0 1 1 0 0 1 1
[2] 0 0 0 0 1 0 0 0
[3] 0 0 0 0 0 1 0 0
[4] 0 0 0 0 0 1 0 1
[5] 0 0 0 0 0 0 1 1
[6] 0 0 0 0 0 0 0 1
[7] 0 0 0 0 0 0 0 0
WEIGHT/COST_MATRIX:
[00][01][02][03][04][05][06][07]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 8 2
[2] 0 0 0 0 5 0 0 0
[3] 0 0 0 0 0 4 0 0
[4] 0 0 0 0 0 7 0 2
[5] 0 0 0 0 0 0 2 5
[6] 0 0 0 0 0 0 0 1
[7] 0 0 0 0 0 0 0 0
CAPACITY_MATRIX:
[00][01][02][03][04][05][06][07]
[0] 0 0 0 0 0 3 0 0
[1] 0 0 4 1 0 0 1 6
[2] 0 0 0 0 7 0 0 0
[3] 0 0 0 0 0 6 0 0
[4] 0 0 0 0 0 9 0 8
[5] 0 0 0 0 0 0 6 5
[6] 0 0 0 0 0 0 0 1
[7] 0 0 0 0 0 0 0 0
#+end_example
** Shimbell method
#+begin_example
SHIMBELL METHOD EDGE COUNT: 2
MIN PATH MATRIX:
[000][001][002][003][004][005][006][007]
[0] inf inf inf inf inf inf inf 10
[1] inf inf inf inf inf 16 8 11
[2] inf inf inf inf inf inf 14 17
[3] inf inf inf inf inf inf inf 7
[4] inf inf inf inf inf inf inf 10
[5] inf inf inf inf inf inf inf inf
[6] inf inf inf inf inf inf inf inf
[7] inf inf inf inf inf inf inf inf
#+end_example
** Route count
#+begin_example
FROM: 0
TO: 7
ROUTE COUNT FROM 0 TO 7: 2
FROM: 2
TO: 7
ROUTE COUNT FROM 2 TO 7: 3
FROM: 5
TO: 0
NO ROUTES FROM 5 TO 0
#+end_example
** Dijkstra's algorithm
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph2.png]]
#+begin_example
MIN
FROM: 2
TO: 7
DISTANCEVECTOR: (inf inf inf 0 inf 5 12 14 7)
PATH: 2 -> 4 -> 7
FROM: 0
TO: 7
DISTANCE VECTOR: (0 0 inf inf inf inf 7 9 10)
PATH: 0 -> 5 -> 6 -> 7
FROM: 2
TO: 0
DISTANCE VECTOR: (inf inf inf 0 inf 5 12 14 7)
NO PATH FROM 2 TO 0
#+end_example
** The Floyd-Warshall algorithm
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph3-1.png]]
#+attr_html: :width 800em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph3-2.png]]
#+begin_example
MAX
FROM: 2
TO: 7
DISTANCE MATRIX:
[0] [1] [2] [3] [4] [5] [6] [7]
[0] 0-inf-inf-inf-inf 7 9 12
[1]-inf 0 4 2 9 16 18 21
[2]-inf-inf 0-inf 5 12 14 17
[3]-inf-inf-inf 0-inf 4 6 9
[4]-inf-inf-inf-inf 0 7 9 12
[5]-inf-inf-inf-inf-inf 0 2 5
[6]-inf-inf-inf-inf-inf-inf 0 1
[7]-inf-inf-inf-inf-inf-inf-inf 0
PATH: 2 -> 4 -> 5 -> 7
#+end_example
** The Ford–Fulkerson algorithm
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph4.png]]
#+begin_example
FROM: 2
TO: 7
MAX_FLOW: 7
FROM: 4
TO: 7
MAX_FLOW: 14
#+end_example
** Calculation of the minimum cost flow
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph5.png]]
#+begin_example
FROM: 4
TO: 7
REQUIRED_FLOW: [14*2/3] = 9
FLOW_MATRIX:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 0 0 0
[1] 0 0 0 0 0 0 0 0
[2] 0 0 0 0 0 0 0 0
[3] 0 0 0 0 0 0 0 0
[4] 0 0 0 0 0 1 0 8
[5] 0 0 0 0 0 0 1 0
[6] 0 0 0 0 0 0 0 1
[7] 0 0 0 0 0 0 0 0
MIN_COST: 26
#+end_example
** Determining the number of possible spanning trees
#+begin_example
KIRCHHOFF_MATRIX:
[000][001][002][003][004][005][006][007]
[0] 1 0 0 0 0 -1 0 0
[1] 0 4 -1 -1 0 0 -1 -1
[2] 0 -1 2 0 -1 0 0 0
[3] 0 -1 0 2 0 -1 0 0
[4] 0 0 -1 0 3 -1 0 -1
[5] -1 0 0 -1 -1 5 -1 -1
[6] 0 -1 0 0 0 -1 3 -1
[7] 0 -1 0 0 -1 -1 -1 4
SPANNING TREE COUNT 181
#+end_example
** Prim, Borovka, and Prufer codes
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph6.png]]
#+begin_example
PRIM
MINIMUM_SPANNING_TREE_WEIGHTS:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 0 2
[2] 0 4 0 0 0 0 0 0
[3] 0 2 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 2
[5] 7 0 0 0 0 0 2 0
[6] 0 0 0 0 0 2 0 1
[7] 0 2 0 0 2 0 1 0
TOTAL_WEIGHT: 20
ITERATION_COUNT: 448
MINIMAL_SPANNING_TREE:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 0 2
[2] 0 4 0 0 0 0 0 0
[3] 0 2 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 2
[5] 7 0 0 0 0 0 2 0
[6] 0 0 0 0 0 2 0 1
[7] 0 2 0 0 2 0 1 0
PRUFER_CODE: 5 1 1 7 7 6 7
SAVED_WEIGHTS: 7 4 2 2 2 2 1
DECODED_MINIMAL_SPANNING_TREE:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 0 2
[2] 0 4 0 0 0 0 0 0
[3] 0 2 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 2
[5] 7 0 0 0 0 0 2 0
[6] 0 0 0 0 0 2 0 1
[7] 0 2 0 0 2 0 1 0
Success, matrices the same!
#+end_example
#+begin_example
BORUVKA
MINIMUM_SPANNING_TREE_WEIGHTS:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 0 2
[2] 0 4 0 0 0 0 0 0
[3] 0 2 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 2
[5] 7 0 0 0 0 0 2 0
[6] 0 0 0 0 0 2 0 1
[7] 0 2 0 0 2 0 1 0
TOTAL_WEIGHT: 20
ITERATION_COUNT: 44
MINIMAL_SPANNING_TREE:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 0 2
[2] 0 4 0 0 0 0 0 0
[3] 0 2 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 2
[5] 7 0 0 0 0 0 2 0
[6] 0 0 0 0 0 2 0 1
[7] 0 2 0 0 2 0 1 0
PRUFER_CODE: 5 1 1 7 7 6 7
SAVED_WEIGHTS: 7 4 2 2 2 2 1
DECODED_MINIMAL_SPANNING_TREE:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 0 7 0 0
[1] 0 0 4 2 0 0 0 2
[2] 0 4 0 0 0 0 0 0
[3] 0 2 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 2
[5] 7 0 0 0 0 0 2 0
[6] 0 0 0 0 0 2 0 1
[7] 0 2 0 0 2 0 1 0
Success, matrices the same!
#+end_example
** Euler
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph7.png]]
#+begin_example
Added edge: 0 -> 4 (9/6)
Removed edge: 5 -> 6
ADJECENCY_MATRIX:
[000][001][002][003][004][005][006][007]
[0] 0 0 0 0 1 1 0 0
[1] 0 0 1 1 0 0 1 1
[2] 0 0 0 0 1 0 0 0
[3] 0 0 0 0 0 1 0 0
[4] 0 0 0 0 0 1 0 1
[5] 0 0 0 0 0 0 0 1
[6] 0 0 0 0 0 0 0 1
[7] 0 0 0 0 0 0 0 0
EULER_CYCLE: 0 -> 5 -> 7 -> 6 -> 1 -> 7 -> 4 -> 5 -> 3 -> 1 -> 2 -> 4 -> 0
#+end_example
** Hamilton
#+attr_html: :width 500em
[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph8.png]]
#+begin_example
Added edge: 0 -> 2 (3/1)
CYCLES_TOTAL: 16
All cycles are saved here: hamiltonian-cycles.txt
Cycle with minimum weight (30): 0 -> 2 -> 4 -> 7 -> 6 -> 1 -> 3 -> 5 -> 0
#+end_example
* Unlicense
#+include: UNLICENSE verse
* Footnotes
[fn:1] Original text:
#+HTML: <i>
#+begin_quote
1. Сформировать случайным образом связный ациклический граф в
соответствии с заданным распределением (параметры распределения
задаются как константы) с необходимым количеством вершин.
Распределение лучше всего брать из справочника Вадзинского.
2. Реализовать метод Шимбелла на полученном графе (пользователь вводит
количество ребер).
3. Определить возможность построения маршрута от одной заданной точки
до другой (вершины вводит пользователь) и указывать количество
таковых маршрутов.
#+end_quote
#+HTML: </i>
[fn:2] Original text:
#+HTML: <i>
#+begin_quote
1. Для заданных графов (случайно сгенерированных в предыдущей работе)
необходимо сгенерировать весовую матрицу (положительную или с
отрицательными весами -- выбирает пользователь) и найти кратчайший
путь для двух выбранных пользователем точек. Пользователь вводит
номера вершин начальной и конечной. В результате выводится не
только расстояние, но и сам путь в виде последовательности
вершин. Для алгоритмов Дейкстры и Беллмана-Форда необходимо
выводить вектор расстояний, для Флойда-Уоршалла -- матрицу
расстояний. Реализуемые алгоритмы:
- *классический алгоритм Дейкстры*
- *алгоритм Флойда-Уоршалла*
- *Нахождение максимального пути* (для заданных пользователем вершин)
2. Сравнить скорости работы данных алгоритмов (по количеству
итераций).
#+end_quote
#+HTML: </i>
[fn:3] Original text:
#+HTML: <i>
#+begin_quote
1. Сформировать связный ациклический граф случайным образом в
соответствии с заданным распределением. На его основе построить
матрицы пропускных способностей и стоимости.
2. Для полученного графа найти максимальный поток по алгоритму
Форда-Фалкерсона (или любого из перечисленных в лекции).
3. Вычислить поток минимальной стоимости (в качестве величины потока
брать значение, равное ⅔max, где max -- максимальный поток).
Использовать ранее реализованные алгоритмы Дейкстры и/или
Беллмана-Форда.
#+end_quote
#+HTML: </i>
[fn:4] Original text:
#+HTML: <i>
#+begin_quote
1. Для заданных графов (случайно сгенерированных в первой работе),
используя матричную теорему Кирхгофа, найти число остовных деревьев
в исходном графе.
2. Построить минимальный по весу остов для сгенерированного
взвешенного графа, используя алгоритмы: *Прима* и *Борувки*. Сравнить
данные алгоритмы (по количеству итераций).
3. Полученный остов закодировать с помощью кода Прюфера и декодировать
его. Cохранять веса при кодировании обязательно.
#+end_quote
#+HTML: </i>
[fn:5] Original text:
#+HTML: <i>
#+begin_quote
1. Для заданных графов (случайно сгенерированных в первой работе)
проверить, является ли граф эйлеровым и гамильтоновым.
2. Проверить, является ли граф эйлеровым. Если нет, то модифицировать
граф (показывать, что изменено). Построить эйлеров цикл.
3. Проверить, является ли граф гамильтоновым. Если нет, то
модифицировать граф (показывать, что изменено). Решить задачу
коммивояжера на гамильтоновом графе (все гамильтоновы циклы с
суммарным весом выводим либо на экран, если их мало, либо в файл).
За реализованные эвристики отдельные бонусы (по умолчанию -- полный
перебор).
#+end_quote
#+HTML: </i>
|