aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 03:20:46 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 04:21:37 +0000
commit556fea05affe6fe8866557d42b6c1ef6559d7880 (patch)
treef8de5473f16e65fcbe10f280b4cf54ee7e32b5b7
downloadlab-01-05-556fea05affe6fe8866557d42b6c1ef6559d7880.tar.gz
publishHEADmaster
-rw-r--r--.dir-locals.el4
-rw-r--r--.envrc18
-rw-r--r--.gitignore5
-rw-r--r--README.org422
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild.sh6
-rw-r--r--channels-lock.scm21
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty23
-rw-r--r--doc/gost/gost-7-32-counters.sty37
-rw-r--r--doc/gost/gost-7-32-headings.sty98
-rw-r--r--doc/gost/gost-7-32-lists.sty15
-rw-r--r--doc/gost/gost-7-32-tables.sty29
-rw-r--r--doc/gost/gost-7-32-toc.sty34
-rw-r--r--doc/gost/gost-7-32.cls62
-rw-r--r--doc/ox-init.el32
-rw-r--r--doc/report.org2050
-rw-r--r--doc/setup.org45
-rw-r--r--doc/spbstu-report.cls73
-rw-r--r--manifest.scm58
-rw-r--r--src/config.h66
-rw-r--r--src/distribution-test.c63
-rw-r--r--src/distribution.c57
-rw-r--r--src/distribution.h22
-rw-r--r--src/dynamic-array.h74
-rw-r--r--src/graph.c1311
-rw-r--r--src/graph.h71
-rw-r--r--src/main.c580
-rw-r--r--src/utils.c108
-rw-r--r--src/utils.h33
30 files changed, 5498 insertions, 0 deletions
diff --git a/.dir-locals.el b/.dir-locals.el
new file mode 100644
index 0000000..fffb06a
--- /dev/null
+++ b/.dir-locals.el
@@ -0,0 +1,4 @@
1;;; Directory Local Variables -*- no-byte-compile: t -*-
2;;; For more information see (info "(emacs) Directory Variables")
3
4((c-ts-mode . ((compile-command . "bear -- ./build.sh"))))
diff --git a/.envrc b/.envrc
new file mode 100644
index 0000000..5e9e6bf
--- /dev/null
+++ b/.envrc
@@ -0,0 +1,18 @@
1CHANNELS=./channels-lock.scm
2MANIFEST=./manifest.scm
3LOAD_PATH=./lib
4ROOT=./.guix-shell
5
6TIME_MACHINE_FLAGS+=" --channels=$CHANNELS"
7SHELL_FLAGS+=" --manifest=$MANIFEST"
8SHELL_FLAGS+=" --search-paths"
9SHELL_FLAGS+=" --root=$ROOT"
10SHELL_FLAGS+=" --load-path=$LOAD_PATH"
11
12use_guix_shell() {
13 test -d "$ROOT" && unlink "$ROOT"
14 eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")"
15}
16
17use guix_shell
18export TEXINPUTS=${TEXINPUTS}:./:./gost/
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0438db1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
1*.pdf
2*.png
3*.html
4/distribution-test
5/main
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..59ddc53
--- /dev/null
+++ b/README.org
@@ -0,0 +1,422 @@
1#+title: Interactive graph visualizer and laboratory suite
2
3* Tasks
4** Random DAG generation and shimbel path metrics[fn:1]
51. Generate a randomly connected acyclic graph according to a given
6 distribution (distribution parameters set as constants) with the
7 required number of vertices. The distribution is best taken from
8 the Wadzinski handbook.
92. Implement the Shimbell method on the resulting graph (the user
10 enters number of edges).
113. Determine the possibility of building a route from one specified
12 point to another one (the vertex is entered by the user) and find
13 the number of such routes.
14
15** Shortest paths and algorithm performance comparison[fn:2]
161. For the given graphs (randomly generated in the previous task) it
17 is necessary to generate a weight matrix (positive or with negative
18 weights -- the user chooses) and find the shortest path for two
19 points selected by the user. The user enters the numbers of the
20 starting and ending vertices. As a result, not only the distance
21 is displayed, but also the path itself in the form of a sequence of
22 vertices. For Dijkstra’s and Bellman‑Ford’s algorithms, it is
23 necessary output the distance vector, for Floyd-Warshall -- the
24 matrix distances. Implemented algorithms:
25 - *classic Dijkstra algorithm*
26 - *the Floyd-Warshall algorithm*
27 - *Finding the maximum path* (for user-defined vertices)
282. Compare the speeds of these algorithms (by number of iterations).
29
30** Maximum flow and minimum-cost network flows[fn:3]
311. Form a connected acyclic graph randomly in according to the
32 specified distribution. Based on it, build throughput and cost
33 matrices.
342. For the resulting graph, find the maximum flow using the algorithm
35 Ford-Fulkerson (or any of those listed in the lecture).
363. Calculate the minimum cost flow (as the flow value take a value
37 equal to ⅔max, where max is the maximum flow). Use previously
38 implemented Dijkstra and/or Bellman-Ford algorithms.
39
40** Spanning trees, matrix-tree theorem, and Prüfer codes[fn:4]
411. For the given graphs (randomly generated in the first task), using
42 Kirchhoff’s matrix theorem, find the number of spanning trees in
43 the original graph.
442. Construct a minimum‑weight spanning tree for the generated weighted
45 graph using the *Prim* and *Boruvka* algorithms. Compare The given
46 algorithms (by the number of iterations).
473. Encode the resulting skeleton using the Prüfer code and decode it.
48 his. It is essential to maintain the weights during encoding.
49
50** Eulerian, Hamiltonian, and traveling salesman problems[fn:5]
511. For the given graphs (randomly generated in the first task), check
52 whether the graph is Eulerian and Hamiltonian.
532. Check whether the graph is Eulerian. If not, modify the graph
54 (show what was changed). Construct an Eulerian cycle.
553. Check whether the graph is Hamiltonian. If not, modify the graph
56 (show what was changed). Solve the problem. The traveling
57 salesman problem on a Hamiltonian graph (we output all Hamiltonian
58 cycles with a total weight either to the screen if there are few of
59 them, or to a file). There are separate bonuses for implemented
60 heuristics (by default, a complete search).
61
62* Documentation
63The exported report can be found at [[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/report.pdf][this link]].
64
65* Showcase
66** Distribution of the random number generator
67#+attr_html: :width 500em
68[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/distribution-my.png]]
69
70** Creation of graph with 8 vertices
71#+attr_html: :width 800em
72[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph1.png]]
73#+begin_example
74ADJECENCY_MATRIX:
75 [00][01][02][03][04][05][06][07]
76[0] 0 0 0 0 0 1 0 0
77[1] 0 0 1 1 0 0 1 1
78[2] 0 0 0 0 1 0 0 0
79[3] 0 0 0 0 0 1 0 0
80[4] 0 0 0 0 0 1 0 1
81[5] 0 0 0 0 0 0 1 1
82[6] 0 0 0 0 0 0 0 1
83[7] 0 0 0 0 0 0 0 0
84
85WEIGHT/COST_MATRIX:
86 [00][01][02][03][04][05][06][07]
87[0] 0 0 0 0 0 7 0 0
88[1] 0 0 4 2 0 0 8 2
89[2] 0 0 0 0 5 0 0 0
90[3] 0 0 0 0 0 4 0 0
91[4] 0 0 0 0 0 7 0 2
92[5] 0 0 0 0 0 0 2 5
93[6] 0 0 0 0 0 0 0 1
94[7] 0 0 0 0 0 0 0 0
95
96CAPACITY_MATRIX:
97 [00][01][02][03][04][05][06][07]
98[0] 0 0 0 0 0 3 0 0
99[1] 0 0 4 1 0 0 1 6
100[2] 0 0 0 0 7 0 0 0
101[3] 0 0 0 0 0 6 0 0
102[4] 0 0 0 0 0 9 0 8
103[5] 0 0 0 0 0 0 6 5
104[6] 0 0 0 0 0 0 0 1
105[7] 0 0 0 0 0 0 0 0
106#+end_example
107
108** Shimbell method
109#+begin_example
110SHIMBELL METHOD EDGE COUNT: 2
111MIN PATH MATRIX:
112 [000][001][002][003][004][005][006][007]
113[0] inf inf inf inf inf inf inf 10
114[1] inf inf inf inf inf 16 8 11
115[2] inf inf inf inf inf inf 14 17
116[3] inf inf inf inf inf inf inf 7
117[4] inf inf inf inf inf inf inf 10
118[5] inf inf inf inf inf inf inf inf
119[6] inf inf inf inf inf inf inf inf
120[7] inf inf inf inf inf inf inf inf
121#+end_example
122
123** Route count
124#+begin_example
125FROM: 0
126TO: 7
127ROUTE COUNT FROM 0 TO 7: 2
128
129FROM: 2
130TO: 7
131ROUTE COUNT FROM 2 TO 7: 3
132
133FROM: 5
134TO: 0
135NO ROUTES FROM 5 TO 0
136#+end_example
137
138** Dijkstra's algorithm
139#+attr_html: :width 500em
140[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph2.png]]
141#+begin_example
142MIN
143FROM: 2
144TO: 7
145DISTANCEVECTOR: (inf inf inf 0 inf 5 12 14 7)
146PATH: 2 -> 4 -> 7
147
148FROM: 0
149TO: 7
150DISTANCE VECTOR: (0 0 inf inf inf inf 7 9 10)
151PATH: 0 -> 5 -> 6 -> 7
152
153FROM: 2
154TO: 0
155DISTANCE VECTOR: (inf inf inf 0 inf 5 12 14 7)
156NO PATH FROM 2 TO 0
157
158#+end_example
159
160** The Floyd-Warshall algorithm
161#+attr_html: :width 500em
162[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph3-1.png]]
163#+attr_html: :width 800em
164[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph3-2.png]]
165#+begin_example
166MAX
167FROM: 2
168TO: 7
169DISTANCE MATRIX:
170 [0] [1] [2] [3] [4] [5] [6] [7]
171[0] 0-inf-inf-inf-inf 7 9 12
172[1]-inf 0 4 2 9 16 18 21
173[2]-inf-inf 0-inf 5 12 14 17
174[3]-inf-inf-inf 0-inf 4 6 9
175[4]-inf-inf-inf-inf 0 7 9 12
176[5]-inf-inf-inf-inf-inf 0 2 5
177[6]-inf-inf-inf-inf-inf-inf 0 1
178[7]-inf-inf-inf-inf-inf-inf-inf 0
179PATH: 2 -> 4 -> 5 -> 7
180#+end_example
181
182** The Ford–Fulkerson algorithm
183#+attr_html: :width 500em
184[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph4.png]]
185#+begin_example
186FROM: 2
187TO: 7
188MAX_FLOW: 7
189
190FROM: 4
191TO: 7
192MAX_FLOW: 14
193#+end_example
194
195** Calculation of the minimum cost flow
196#+attr_html: :width 500em
197[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph5.png]]
198#+begin_example
199FROM: 4
200TO: 7
201REQUIRED_FLOW: [14*2/3] = 9
202FLOW_MATRIX:
203 [000][001][002][003][004][005][006][007]
204[0] 0 0 0 0 0 0 0 0
205[1] 0 0 0 0 0 0 0 0
206[2] 0 0 0 0 0 0 0 0
207[3] 0 0 0 0 0 0 0 0
208[4] 0 0 0 0 0 1 0 8
209[5] 0 0 0 0 0 0 1 0
210[6] 0 0 0 0 0 0 0 1
211[7] 0 0 0 0 0 0 0 0
212MIN_COST: 26
213#+end_example
214
215** Determining the number of possible spanning trees
216#+begin_example
217KIRCHHOFF_MATRIX:
218 [000][001][002][003][004][005][006][007]
219[0] 1 0 0 0 0 -1 0 0
220[1] 0 4 -1 -1 0 0 -1 -1
221[2] 0 -1 2 0 -1 0 0 0
222[3] 0 -1 0 2 0 -1 0 0
223[4] 0 0 -1 0 3 -1 0 -1
224[5] -1 0 0 -1 -1 5 -1 -1
225[6] 0 -1 0 0 0 -1 3 -1
226[7] 0 -1 0 0 -1 -1 -1 4
227SPANNING TREE COUNT 181
228#+end_example
229
230** Prim, Borovka, and Prufer codes
231#+attr_html: :width 500em
232[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph6.png]]
233#+begin_example
234PRIM
235MINIMUM_SPANNING_TREE_WEIGHTS:
236 [000][001][002][003][004][005][006][007]
237[0] 0 0 0 0 0 7 0 0
238[1] 0 0 4 2 0 0 0 2
239[2] 0 4 0 0 0 0 0 0
240[3] 0 2 0 0 0 0 0 0
241[4] 0 0 0 0 0 0 0 2
242[5] 7 0 0 0 0 0 2 0
243[6] 0 0 0 0 0 2 0 1
244[7] 0 2 0 0 2 0 1 0
245TOTAL_WEIGHT: 20
246ITERATION_COUNT: 448
247MINIMAL_SPANNING_TREE:
248 [000][001][002][003][004][005][006][007]
249[0] 0 0 0 0 0 7 0 0
250[1] 0 0 4 2 0 0 0 2
251[2] 0 4 0 0 0 0 0 0
252[3] 0 2 0 0 0 0 0 0
253[4] 0 0 0 0 0 0 0 2
254[5] 7 0 0 0 0 0 2 0
255[6] 0 0 0 0 0 2 0 1
256[7] 0 2 0 0 2 0 1 0
257PRUFER_CODE: 5 1 1 7 7 6 7
258SAVED_WEIGHTS: 7 4 2 2 2 2 1
259DECODED_MINIMAL_SPANNING_TREE:
260 [000][001][002][003][004][005][006][007]
261[0] 0 0 0 0 0 7 0 0
262[1] 0 0 4 2 0 0 0 2
263[2] 0 4 0 0 0 0 0 0
264[3] 0 2 0 0 0 0 0 0
265[4] 0 0 0 0 0 0 0 2
266[5] 7 0 0 0 0 0 2 0
267[6] 0 0 0 0 0 2 0 1
268[7] 0 2 0 0 2 0 1 0
269Success, matrices the same!
270#+end_example
271
272#+begin_example
273BORUVKA
274MINIMUM_SPANNING_TREE_WEIGHTS:
275 [000][001][002][003][004][005][006][007]
276[0] 0 0 0 0 0 7 0 0
277[1] 0 0 4 2 0 0 0 2
278[2] 0 4 0 0 0 0 0 0
279[3] 0 2 0 0 0 0 0 0
280[4] 0 0 0 0 0 0 0 2
281[5] 7 0 0 0 0 0 2 0
282[6] 0 0 0 0 0 2 0 1
283[7] 0 2 0 0 2 0 1 0
284TOTAL_WEIGHT: 20
285ITERATION_COUNT: 44
286MINIMAL_SPANNING_TREE:
287 [000][001][002][003][004][005][006][007]
288[0] 0 0 0 0 0 7 0 0
289[1] 0 0 4 2 0 0 0 2
290[2] 0 4 0 0 0 0 0 0
291[3] 0 2 0 0 0 0 0 0
292[4] 0 0 0 0 0 0 0 2
293[5] 7 0 0 0 0 0 2 0
294[6] 0 0 0 0 0 2 0 1
295[7] 0 2 0 0 2 0 1 0
296PRUFER_CODE: 5 1 1 7 7 6 7
297SAVED_WEIGHTS: 7 4 2 2 2 2 1
298DECODED_MINIMAL_SPANNING_TREE:
299 [000][001][002][003][004][005][006][007]
300[0] 0 0 0 0 0 7 0 0
301[1] 0 0 4 2 0 0 0 2
302[2] 0 4 0 0 0 0 0 0
303[3] 0 2 0 0 0 0 0 0
304[4] 0 0 0 0 0 0 0 2
305[5] 7 0 0 0 0 0 2 0
306[6] 0 0 0 0 0 2 0 1
307[7] 0 2 0 0 2 0 1 0
308Success, matrices the same!
309#+end_example
310
311** Euler
312#+attr_html: :width 500em
313[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph7.png]]
314#+begin_example
315Added edge: 0 -> 4 (9/6)
316Removed edge: 5 -> 6
317ADJECENCY_MATRIX:
318 [000][001][002][003][004][005][006][007]
319[0] 0 0 0 0 1 1 0 0
320[1] 0 0 1 1 0 0 1 1
321[2] 0 0 0 0 1 0 0 0
322[3] 0 0 0 0 0 1 0 0
323[4] 0 0 0 0 0 1 0 1
324[5] 0 0 0 0 0 0 0 1
325[6] 0 0 0 0 0 0 0 1
326[7] 0 0 0 0 0 0 0 0
327EULER_CYCLE: 0 -> 5 -> 7 -> 6 -> 1 -> 7 -> 4 -> 5 -> 3 -> 1 -> 2 -> 4 -> 0
328#+end_example
329
330** Hamilton
331#+attr_html: :width 500em
332[[https://git.michalec.dev/uni/term-04/graph-theory/lab-01-05/graph8.png]]
333#+begin_example
334Added edge: 0 -> 2 (3/1)
335CYCLES_TOTAL: 16
336All cycles are saved here: hamiltonian-cycles.txt
337Cycle with minimum weight (30): 0 -> 2 -> 4 -> 7 -> 6 -> 1 -> 3 -> 5 -> 0
338#+end_example
339
340* Unlicense
341#+include: UNLICENSE verse
342
343* Footnotes
344[fn:1] Original text:
345#+HTML: <i>
346#+begin_quote
3471. Сформировать случайным образом связный ациклический граф в
348 соответствии с заданным распределением (параметры распределения
349 задаются как константы) с необходимым количеством вершин.
350 Распределение лучше всего брать из справочника Вадзинского.
3512. Реализовать метод Шимбелла на полученном графе (пользователь вводит
352 количество ребер).
3533. Определить возможность построения маршрута от одной заданной точки
354 до другой (вершины вводит пользователь) и указывать количество
355 таковых маршрутов.
356#+end_quote
357#+HTML: </i>
358
359[fn:2] Original text:
360#+HTML: <i>
361#+begin_quote
3621. Для заданных графов (случайно сгенерированных в предыдущей работе)
363 необходимо сгенерировать весовую матрицу (положительную или с
364 отрицательными весами -- выбирает пользователь) и найти кратчайший
365 путь для двух выбранных пользователем точек. Пользователь вводит
366 номера вершин начальной и конечной. В результате выводится не
367 только расстояние, но и сам путь в виде последовательности
368 вершин. Для алгоритмов Дейкстры и Беллмана-Форда необходимо
369 выводить вектор расстояний, для Флойда-Уоршалла -- матрицу
370 расстояний. Реализуемые алгоритмы:
371 - *классический алгоритм Дейкстры*
372 - *алгоритм Флойда-Уоршалла*
373 - *Нахождение максимального пути* (для заданных пользователем вершин)
3742. Сравнить скорости работы данных алгоритмов (по количеству
375 итераций).
376#+end_quote
377#+HTML: </i>
378
379[fn:3] Original text:
380#+HTML: <i>
381#+begin_quote
3821. Сформировать связный ациклический граф случайным образом в
383 соответствии с заданным распределением. На его основе построить
384 матрицы пропускных способностей и стоимости.
3852. Для полученного графа найти максимальный поток по алгоритму
386 Форда-Фалкерсона (или любого из перечисленных в лекции).
3873. Вычислить поток минимальной стоимости (в качестве величины потока
388 брать значение, равное ⅔max, где max -- максимальный поток).
389 Использовать ранее реализованные алгоритмы Дейкстры и/или
390 Беллмана-Форда.
391#+end_quote
392#+HTML: </i>
393
394[fn:4] Original text:
395#+HTML: <i>
396#+begin_quote
3971. Для заданных графов (случайно сгенерированных в первой работе),
398 используя матричную теорему Кирхгофа, найти число остовных деревьев
399 в исходном графе.
4002. Построить минимальный по весу остов для сгенерированного
401 взвешенного графа, используя алгоритмы: *Прима* и *Борувки*. Сравнить
402 данные алгоритмы (по количеству итераций).
4033. Полученный остов закодировать с помощью кода Прюфера и декодировать
404 его. Cохранять веса при кодировании обязательно.
405#+end_quote
406#+HTML: </i>
407
408[fn:5] Original text:
409#+HTML: <i>
410#+begin_quote
4111. Для заданных графов (случайно сгенерированных в первой работе)
412 проверить, является ли граф эйлеровым и гамильтоновым.
4132. Проверить, является ли граф эйлеровым. Если нет, то модифицировать
414 граф (показывать, что изменено). Построить эйлеров цикл.
4153. Проверить, является ли граф гамильтоновым. Если нет, то
416 модифицировать граф (показывать, что изменено). Решить задачу
417 коммивояжера на гамильтоновом графе (все гамильтоновы циклы с
418 суммарным весом выводим либо на экран, если их мало, либо в файл).
419 За реализованные эвристики отдельные бонусы (по умолчанию -- полный
420 перебор).
421#+end_quote
422#+HTML: </i>
diff --git a/UNLICENSE b/UNLICENSE
new file mode 100644
index 0000000..efb9808
--- /dev/null
+++ b/UNLICENSE
@@ -0,0 +1,24 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..1a521f3
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,6 @@
1#!/bin/sh
2
3set -xe
4
5gcc -o main -I./src/ -I./lib/ -std=gnu99 -lraylib -lgsl -lopenblas -lm src/distribution.c src/utils.c src/graph.c src/main.c
6gcc -o distribution-test -I./src/ -I./lib/ -std=gnu99 -lraylib src/distribution.c src/distribution-test.c
diff --git a/channels-lock.scm b/channels-lock.scm
new file mode 100644
index 0000000..c689b95
--- /dev/null
+++ b/channels-lock.scm
@@ -0,0 +1,21 @@
1(use-modules (guix channels))
2
3(list
4 (channel
5 (name 'guix)
6 (branch "master")
7 (url "https://git.savannah.gnu.org/git/guix.git")
8 (commit "26a8b63ec30ad101e860c8f4df0bd7e4d1a825b1")
9 (introduction (make-channel-introduction
10 "d264237d55ca5e2c756cc7a44374a7dbca850505"
11 (openpgp-fingerprint
12 "BBB0 2DDF 2CEA F6A8 0D1D E643 A2A0 6DF2 A33A 54FA"))))
13 (channel
14 (name 'nonguix)
15 (url "https://gitlab.com/nonguix/nonguix")
16 (commit "926a17ea317d1f45c9fc06bcf49213eaad286500")
17 (introduction
18 (make-channel-introduction
19 "897c1a470da759236cc11798f4e0a5f7d4d59fbc"
20 (openpgp-fingerprint
21 "2A39 3FFF 68F4 EF7A 3D29 12AF 6F51 20A0 22FB B2D5")))))
diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty
new file mode 100644
index 0000000..dca60fa
--- /dev/null
+++ b/doc/gost/gost-7-32-bibliography.sty
@@ -0,0 +1,57 @@
1\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017]
2
3\def\UrlBreaks{\do\/\do-}
4\RequirePackage{url}
5
6\newdimen\bibindent
7\renewenvironment{thebibliography}[1]{
8 \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}%
9 \list{\@biblabel{\@arabic\c@enumiv}}%
10 {\settowidth\labelwidth{\@biblabel{#1}}%
11 \leftmargin\labelwidth
12 \advance\leftmargin\labelsep
13 \@openbib@code
14 \usecounter{enumiv}%
15 \let\p@enumiv\@empty
16 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
17 \sloppy\clubpenalty4000\widowpenalty4000%
18 \sfcode`\.\@m
19}{
20 \setcounter{totalbib}{\c@enumiv}%
21 \def\@noitemerr
22 {\@latex@warning{Empty `thebibliography' environment}}%
23 \endlist
24}
25\renewcommand\@biblabel{}%
26\setlength\bibindent{1.5em}
27
28% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И.
29%\makeatletter
30\renewcommand*{\@biblabel}[1]{\hfill#1.}
31
32
33%
34% Remove References header completely
35% Stolen from original article.cls
36%
37\makeatletter
38\renewenvironment{thebibliography}[1]{%
39% \usection{\refname}%
40% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
41 \list{\@biblabel{\@arabic\c@enumiv}}%
42 {\settowidth\labelwidth{\@biblabel{#1}}%
43 \leftmargin\labelwidth
44 \advance\leftmargin\labelsep
45 \@openbib@code
46 \usecounter{enumiv}%
47 \let\p@enumiv\@empty
48 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
49 \sloppy
50 \clubpenalty4000
51 \@clubpenalty \clubpenalty
52 \widowpenalty4000%
53 \sfcode`\.\@m}
54 {\def\@noitemerr
55 {\@latex@warning{Empty `thebibliography' environment}}%
56 \endlist}
57\makeatother
diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty
new file mode 100644
index 0000000..1dff33f
--- /dev/null
+++ b/doc/gost/gost-7-32-captions.sty
@@ -0,0 +1,23 @@
1\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{caption}
4\RequirePackage{subcaption}
5
6%
7% Table caption aligned to the left with dash as a separator
8%
9\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off}
10
11%
12% Dash as separator in figure caption and centering
13%
14\captionsetup[figure]{labelsep=endash, justification=centering}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, justification=centering}
20
21\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}}
22\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}}
23\addto\captionsrussian{\captionsetup[listing]{name=Листинг}}
diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty
new file mode 100644
index 0000000..d694c93
--- /dev/null
+++ b/doc/gost/gost-7-32-counters.sty
@@ -0,0 +1,37 @@
1\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017]
2
3%
4% Values for capital russian letters counter
5%
6\makeatletter
7\newcommand\AlphRus[1]{%
8 \expandafter \@AlphRus \csname c@#1\endcsname
9}
10
11\newcommand\@AlphRus[1]{%
12 \ifcase #1%
13 \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or
14 Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or
15 Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я%
16 \else \@ctrerr
17\fi
18}
19\makeatother
20
21%
22% Values for lowercase russian letters counter
23%
24\makeatletter
25\newcommand\alphRus[1]{%
26 \expandafter \@alphRus \csname c@#1\endcsname
27}
28
29\newcommand\@alphRus[1]{%
30 \ifcase #1%
31 \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or
32 л\or м\or н\or п\or р\or с\or т\or у\or ф\or
33 х\or ц\or ш\or щ\or э\or ю\or я%
34 \else \@ctrerr
35\fi
36}
37\makeatother
diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty
new file mode 100644
index 0000000..d0bb40e
--- /dev/null
+++ b/doc/gost/gost-7-32-headings.sty
@@ -0,0 +1,98 @@
1\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{titlesec}
4\RequirePackage{titling}
5\RequirePackage{setspace}
6
7\RequirePackage{gost-7-32-counters}
8
9%
10% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection
11%
12\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{}
13\titlespacing{\section}{0cm}{0cm}{0.5cm}
14
15\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{}
16\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm}
17
18\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent]
19\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm}
20
21%
22% Make special headings, that have their own formatting rules:
23% - centered
24% - all-caps
25% - bold
26%
27% Only three of them must appear in TOC: introduction, conclusion and references
28%
29\newcommand{\introduction}{
30 \addcontentsline{toc}{section}{ВВЕДЕНИЕ}
31 \begin{center}
32 \bfseries\large
33 ВВЕДЕНИЕ
34 \end{center}
35}
36
37\newcommand{\conclusion}{
38 \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ}
39 \begin{center}
40 \bfseries\large
41 ЗАКЛЮЧЕНИЕ
42 \end{center}
43}
44
45\newcommand{\references}{
46 \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}
47 \begin{center}
48 \bfseries\large
49 СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
50 \end{center}
51}
52
53\newcommand{\essay}{
54 \begin{center}
55 \bfseries\large
56 РЕФЕРАТ
57 \end{center}
58}
59
60\newcommand{\definitions}{
61 \begin{center}
62 \bfseries\large
63 ОПРЕДЕЛЕНИЯ
64 \end{center}
65}
66
67\newcommand{\abbreviations}{
68 \begin{center}
69 \bfseries\large
70 ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
71 \end{center}
72}
73
74\newcommand{\defsabbrs}{
75 \begin{center}
76 \bfseries\large
77 ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
78 \end{center}
79}
80
81%
82% Appendices headings. Appendices have autoincrementing number,
83% that is represented with russian letter.
84% This heading must appear in TOC
85%
86\newcounter{appendixcnt}
87\setcounter{appendixcnt}{1}
88
89\renewcommand{\appendix}[1]{
90 \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1}
91 \begin{center}
92 \bfseries\large
93 ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}
94
95 #1
96 \end{center}
97 \stepcounter{appendixcnt}
98}
diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty
new file mode 100644
index 0000000..b68d55f
--- /dev/null
+++ b/doc/gost/gost-7-32-lists.sty
@@ -0,0 +1,15 @@
1\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{enumitem}
4\RequirePackage{gost-7-32-counters}
5
6\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1}
7
8\setlist{nosep}
9\setlist[itemize, 1]{label=\textendash}
10\setlist[itemize, 2]{label=\bullet}
11
12\setlist[enumerate, 2]{label=\alphRus*)}
13
14\setlist[1]{wide=\parindent}
15\setlist[2]{wide=2\parindent, leftmargin=\parindent}
diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty
new file mode 100644
index 0000000..750ab75
--- /dev/null
+++ b/doc/gost/gost-7-32-tables.sty
@@ -0,0 +1,29 @@
1\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tabularx}
4
5%
6% Center-aligned column with automatic width
7%
8\newcolumntype{Y}{>{\centering\arraybackslash}X}
9
10%
11% Right-aligned column with automatic width
12%
13\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
14
15%
16% Table with designations
17%
18\newenvironment{designations}{
19 \noindent
20 \tabularx{\textwidth}{@{}
21 >{\raggedright \arraybackslash \hsize=0.25\hsize}X
22 >{\centering \arraybackslash \hsize=0.05\hsize}X
23 >{\arraybackslash \hsize=0.70\hsize}X
24 }
25}{
26 \endtabularx
27}
28
29\newcommand{\designation}[2]{#1 &---& #2. \\}
diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty
new file mode 100644
index 0000000..c3b835a
--- /dev/null
+++ b/doc/gost/gost-7-32-toc.sty
@@ -0,0 +1,34 @@
1\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017]
2
3%% \RequirePackage{tocloft}
4\RequirePackage[
5 bookmarks=true,
6 colorlinks=true,
7 unicode=true,
8 urlcolor=black,
9 linkcolor=black,
10 anchorcolor=black,
11 citecolor=black,
12 menucolor=black,
13 filecolor=black
14]{hyperref}
15
16%
17% Set custom font styles
18%
19%% \renewcommand{\cftsecfont}{\normalfont}
20%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
21%% \renewcommand{\cftsecpagefont}{\normalsize}
22%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries}
23%% \renewcommand{\cftaftertoctitle}{\hfill\hfill}
24%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries}
25\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{}
26\titlespacing{\tableofcontents}{0cm}{0cm}{1cm}
27
28%
29% Set indents and line spacing
30%
31%% \setlength{\cftbeforesecskip}{0cm}
32%% \setlength{\cftbeforesubsecskip}{0cm}
33%% \setlength{\cftbeforesubsubsecskip}{0cm}
34%% \setlength{\cftbeforeparaskip}{0cm}
diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls
new file mode 100644
index 0000000..c13b00e
--- /dev/null
+++ b/doc/gost/gost-7-32.cls
@@ -0,0 +1,62 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017]
3
4%
5% Supported font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12%
13% Set A4 paper format
14%
15\LoadClass[a4paper]{extarticle}
16
17%
18% Use 1.5 line spacing
19%
20\RequirePackage{setspace}
21\spacing{1.5}
22
23%
24% First paragraph indentation
25%
26\RequirePackage{indentfirst}
27\setlength{\parindent}{12.5mm}
28
29%
30% Page margin
31%
32\RequirePackage[
33 left=2.5cm,
34 right=2cm,
35 top=2cm,
36 bottom=2cm,
37 footskip=1cm,
38]{geometry}
39
40%
41% Use TMR-like font
42%
43\RequirePackage{fontspec}
44\RequirePackage{xunicode}
45\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
46\setmainfont{Times New Roman}
47
48%
49% Use russian language
50%
51\RequirePackage[main=russian, english]{babel}
52\babelhyphenation[russian]{}
53
54%
55% gost-7-32 packages
56%
57\RequirePackage{gost-7-32-headings}
58\RequirePackage{gost-7-32-toc}
59\RequirePackage{gost-7-32-lists}
60\RequirePackage{gost-7-32-bibliography}
61\RequirePackage{gost-7-32-captions}
62\RequirePackage{gost-7-32-tables}
diff --git a/doc/ox-init.el b/doc/ox-init.el
new file mode 100644
index 0000000..913d021
--- /dev/null
+++ b/doc/ox-init.el
@@ -0,0 +1,32 @@
1;;; ox-init --- Initialization script for async org exprort session
2;;; Commentary:
3;;; Code:
4(org-babel-do-load-languages
5 'org-babel-load-languages
6 '((latex . t)
7 (C . t)))
8
9(require 'ox-extra)
10(ox-extras-activate '(ignore-headlines))
11
12(require 'oc-bibtex)
13
14(setq org-latex-src-block-backend 'minted)
15
16(setq org-latex-bib-compiler "biber")
17
18(setq org-latex-remove-logfiles nil)
19
20(setq org-latex-caption-above '(table src-block special-block))
21
22(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f"
23 "%bib %b"
24 "%latex -shell-escape -interaction nonstopmode -output-directory %o %f"))
25(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
26 ("\\section{%s}" . "\\usection{%s}")
27 ("\\subsection{%s}" . "\\subsection*{%s}")
28 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
29 ("\\paragraph{%s}" . "\\paragraph*{%s}")
30 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
31
32;;; ox-init.el ends here
diff --git a/doc/report.org b/doc/report.org
new file mode 100644
index 0000000..ee49ee1
--- /dev/null
+++ b/doc/report.org
@@ -0,0 +1,2050 @@
1#+TITLE: Реализация алгоритмов на графах
2#+AUTHOR: Михалец Мартин
3#+DATE: 2024
4
5#+SETUPFILE: setup.org
6#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНЫХ РАБОТ №1-5}
7#+LATEX_HEADER: \subject{по дисциплине «Теория графов»}
8#+LATEX_HEADER: \reviewertitle{}\reviewer{Востров Алексей Владимирович}
9#+LATEX: \sloppy
10
11* Введение
12:PROPERTIES:
13:UNNUMBERED: t
14:END:
15Данный отчет содержит в себе описание пяти лабораторных работ по
16дисциплине «Теория графов». Лабораторные работы заключаются в
17реализации алгоритмов над случайно сгенерированными связными
18ациклическими графами. Графы сгенерированы при помощи заданного в
19варианте (15) случайного распределения --- Пойя 1.
20
21Список реализованных методов и алгоритмов:
22- Идса --- силовая визуализация графов
23- Шимбелла
24- поиск количества путей между двумя вершинами
25- Дейкстры
26- Флойда-Уоршелла
27- Форда-Фалкерсона
28- нахождение потока минимальной стоимости
29- Прима
30- Борувки
31- Кирхгоффа
32- кодирования и декодирование кодом Прюфера
33- проверки графа на Эйловость
34- проверки графа на Гамильтоновость
35- модификации графа до Эйлерова
36- модификации графа до Гаммильтонова
37- построения Эйлерова цикла
38- решение задачи коммивояжера
39
40* Математическое описание
41** Определение грава
42Граф $G(V, E)$ --- совокупность двух множеств --- негустого множества
43$V$ (множества вершин) и множества $E$ неупорядоченных пар различных
44элементов множества $V$ ($E$ --- множество рёбер)
45#+begin_export latex
46\begin{displaymath}
47 G(V,E) = <V,E>,\quad V \ne \emptyset,\quad E \notin V \times V,\quad E = E^{-1}.
48\end{displaymath}
49#+end_export
50
51Число рёбер обозначается как $q$, число вершин --- $p$.
52
53Связный граф --- граф, содержащий ровно одну компоненту связности.
54Это означает, что между любой парой вершин этого графа существует как
55минимум один путь.
56
57Ациклический граф --- граф, который не содержит циклов.
58
59** Распределение Пойя 1
60Распределение Поя 1 моделирует распределение дискретной случайной
61величины
62
63#+caption: График функции распределения Пойя 1 с параметрами $n = 5, b = 20, r = 20, c = 1$
64#+attr_latex: :height 5cm
65[[./distribution-book.png]]
66
67#+caption: Полученный график функции распределения Пойя 1 с параметрами $n = 9, b = 20, r = 1, c = 10$
68#+attr_latex: :height 5cm
69[[./distribution-my.png]]
70
71Генерирование случайных чисел в соответствии с данным распределением
72происходит по алгоритму, представленному на блок-схеме.
73
74#+caption: Блок-схема алгоритма формирования случайных чисел, имеющих распределение Пойя 1
75#+attr_latex: :height 10cm
76[[./distribution-diagram.png]]
77
78Алгоритм реализует стандартный способ имитационного моделирования
79дискретных случайных величин. (*) Вероятность $p_0 = P(X = 0)$
80вычисляется по формуле:
81#+begin_export latex
82\begin{displaymath}
83 p(0) = \frac
84 {r(r + c)(r + 2c)\ldots[r + (n - 1)c]}
85 {(b + r)(b + r + c)(b + r + 2c)\ldots[b + r (n - 1)c]}.
86\end{displaymath}
87#+end_export
88(**) Функция $\alpha(x)$ вычисляется по формуле $\alpha(x) = (n - 1 -
89x)[b + (x - 1)c]/{x[r + (n - x)c]}$.
90
91Полученная последовательность чисел характеризует распределение
92степеней вершин графа $G(V,E)$
93
94** Пружинный встраиватель Идса
95/Пружинный встраиватель Идса/ -- силовой алгоритм визуализации графов на
96основе законов Гука и Кулона.
97
98Отталкивающие силы:
99#+begin_export latex
100\begin{displaymath}
101 f_{rep}(u,v) = \frac{c_{rep}}{\|p_v - p_u\|^2} \cdot \overrightarrow{p_vp_u}
102\end{displaymath}
103#+end_export
104
105Притягивающие силы:
106#+begin_export latex
107\begin{gather*}
108 f_{spring}(u,v) = c_{spring}\cdot\log\frac{\|p_v - p_u\|}{l} \cdot \overrightarrow{p_vp_u} \\
109 f_{attr}(u,v) = f_{spring}(u,v) - f_{rep}(u,v)
110\end{gather*}
111#+end_export
112
113 #+BEGIN_EXPORT latex
114\begin{algorithm}[H]
115 \begin{algorithmic}[1]
116 \setlength{\baselineskip}{5pt}
117 \Procedure {force\_directed}{$G = (V,E), p = (p_v)_{v \in V}, \varepsilon > 0, K \in \mathbb{N}$}
118 \State $t \leftarrow 1$
119 \While {$t < K$ \And $max_{v \in V}\|F_v(t)\| > \varepsilon$}
120 \ForAll {$u \in V$}
121 \State $F_u(t) \leftarrow \sum_{v \in V}f_{rep}(u,v) + \sum_{v \in V}f_{attr}(u,v)$
122 \EndFor
123 \ForAll {$u \in V$}
124 \State $p_u \leftarrow p_u + \delta(t) \cdot F_u(t)$
125 \EndFor
126 \State $t \leftarrow t + 1$
127 \EndWhile
128 \State \Return $p$
129 \EndProcedure
130 \end{algorithmic}
131\end{algorithm}
132#+END_EXPORT
133
134** Метод Шимбелла
135Данный метод предназначен для определения минимальных (максимальных)
136расстояний между всеми парами вершин взвешенного графа, учитываю число
137рёбер, входящих в соответствующие просты цепи.
138
139Ключом к методу Шимбелла поиска экстремальных путей являются
140специальные операции:
1411. Операция умножения:
142 \[\left\{\begin{aligned}
143 & a \cdot b = b \cdot a \Rightarrow a + b = b + a \\
144 & a \cdot 0 = 0 \cdot a \Rightarrow a + 0 = 0 + a = a \\
145 \end{aligned}\]
1462. Операция сложения:
147 \[ a + b = b + a \Rightarrow \min(a, b) (\text{или\,} \max(a, b)) \]
148
149С помощью данных операции длины кратчайших (или максимальных) путей
150определяются возведением в степень $x$ весовой матрицы $\Omega$, где
151$x$ --- количество рёбер в пути. Элемент $\Omega^x_{ij}$ покажет
152длину экстремального пути длиной в $x$ рёбер из вершины $i$ в вершину
153$j$.
154#+begin_export latex
155\begin{displaymath}
156 \Omega^2_{ij} = \sum_{k=1}^p\omega_{ik}\omega_{kj}
157\end{displaymath}
158#+end_export
159
160Формула для вычисления элементов весовой матрицы $\Omega$ возведённой
161в степень $2$ ($\omega$ --- элемент матрицы $\Omega$)
162
163** Алгоритм Дейкстры
164/Алгоритм Дейкстры/ является жадным алгоритмом. Алгоритм находит
165кратчайшие пути во взвешенном графе от одной вершины до всех
166остальных, если веса дуг неотрицательные.
167
168*Описание работы алгоритма Дейкстры:*
169
170На первой итерации выбрана будет стартовая вершина $s$. Выбранная
171таким образом вершина $v$ отмечается помеченной.
172
173Далее, на текущей итерации, из вершины $v$ рассматриваются все рёбра
174$(v, u)$ исходящие из вершины $v$. Для каждой такой вершины $u$
175алгоритм пытается улучшить значение $d_u$.
176
177Пусть длина текущего ребра равна $l$, тогда $d_u = \min(d_u, d_v +
178l)$.
179
180На этом текущая итерация заканчивается, алгоритм переходит к следующей
181итерации (снова выбирается вершина с наименьшей величиной $d$ и т.д.).
182При этом, после $n$ итерации, все вершины графа станут помеченными, и
183алгоритм свою работу завершает.
184
185Найденные значения $d_v$ и есть искомые длины кратчайших путей из $s$
186в $p$.
187
188*Сложность алгоритма:* $\mathcal{O}(n^2)$.
189
190** Алгоритм Флойда-Уоршелла
191/Алгоритм Флойда-Уоршелла/ находит кратчайшие пути между всеми парами
192вершин (узлов) в графе. Веса рёбер могут быть как положительными, так
193и отрицательными. Для нахождения кратчайших путей между всеми
194вершинами графа используется восходящее динамическое программирование,
195то есть все подзадачи, которые впоследствии понадобятся для решения
196исходной задачи, просчитываются заранее и затем используются.
197
198Идея алгоритма --- разбиение процесса поиска кратчайших путей на фазы.
199
200Перед $k\text{-ой}$ фазой величина $d_{ij}$ равна длине кратчайшего
201пути из вершины $i$ в вершины $j$, если этому пути разрешается заходит
202только в вершины с номерами, меньшимы $k$. на $k\text{-ой}$ фазе мы
203попытаемся улучшисть путь $i \rightarrow j$, пройдя через вершину $k$:
204$d_{ij} = \min(d_{ij}, d_{ik}) = d_{kj})$. Матрица $d$ и является
205искомой матрицей расстояний.
206
207*Сложность алогоритма:* $\mathcal{O}(n^3)$.
208
209** Метод поиска максимального пути
210Сам алгоритм вычисления максимального пути чисто перечислительный. Он
211перебирает все возможные пути от текущей вершины до всех последующих,
212достижимых из текущей вершины.
213
214В данной лабораторной работе было решено просто инвертировать критерии
215в алгоритме Флойда-Уоршелла ($\min \rightarrow \max$) вместе с
216инициализацией вспомогательных данных ($\infty \rightarrow -\infty$).
217
218Данный метод может и не найти самый длинный путь при применении
219алгоритма Дейкстры, так как исплользуются неположительные веса.
220
221** Максимальный поток в сети
222Пусть $G(V, E)$ --- сеть, $s$ и $t$ --- соответственно, источник и
223сток сети. Дуги сети нагружены неотрицательными вещественными
224числами: $E \rightarrow R^+$. Если $u$ и $v$ --- узлы сети, то число
225$c(u,v)$ --- называется /пропускной способносью дуги$(u,v)$/.
226
227/Дивергенцией функции/ $f$ в узле $v$ называется число
228$\operatorname{div}(f, v)$, которое определяется следующим образом:
229
230Функция $f$: $E \rightarrow R$ называется /потоком/ в сети $G$, если:
2311. $\forall(u,v) \inset E: 0 \le f(u,v) \le c(u,b)$, то есть поток
232 через дуге неотрицательный и не превосходит пропускной способности
233 дуги.
2342. $\forall u \in V: \operatorname{div}(f, u) = 0$, то есть
235 дивергенция потока равна нулю во всех узлах, кроме источника и
236 стока.
237
238/Величина потока в сети $G$/ --- сумма всех потоков, выходящих из
239истока, то есть $\omega(f) = \operatorname{div}(f, s)$.
240
241** Алгоритм Форда-Фалкерсона
242Теорема Форда-Фалкерсона: максимальный поток в сети равен минимальной
243пропускной способности разреза, то есть существует поток $f^*$, такой,
244что $\omega(f^*) = \underset{f}{\max} \omega(f) = \underset{P}{\min}
245C(P)$.
246
247На основе данной теоремы реализуется алгоритм Форда-Фалкерсона для
248определения максимального потока в сети, заданной матрицей пропускных
249способностей дуг.
250
251Алгоритм Форда-Фалкерсона решает задачу нахождения максимального
252потока в транспортной сети.
253
254*Сложность алгоритма:* $\mathcal{O}(q \cdot f^*)$.
255
256** Метод поиска потока минимальной стоимости с целевой функцией
257В данном случае целевая функция задает, что поток должен составлять
258как минимум 2/3 максимального потока.
259
260Для поиска потока минимальной стоимости нужно применить алгоритм, для
261нахождения пути минимальной стоимости, например алгоритм
262Беллмана-Форда. После нахождения такого пути по нему пускается
263максимальный поток. Если величина потока достигла 2/3 максимального
264потока, то алгоритм завершается. Пока величина потока меньше,
265обновляются матрицы веса и пропускной стоимости, по которым ищутся
266пути и поток минимальной стоимости.
267
268*Сложность метода при применении алгоритма Беллмана-Форда:* $\mathcal{O}(q^3)$.
269
270** Поиск минимального остова
271/Остовым деревом/ или /остовом графа $G(V,E)$/ называется связный подграф
272без циклов, содержащий все вершины исходного графа. Подгрфа содержит
273часть или все рёбра исходного графа.
274
275/Минимальное остовое дерево/ --- остовое дерево, сумма весов рёбер
276которого минимальна.
277
278/Задача о минимальном остове:/ во взвешенном связном графе найти остов
279минимального веса, то есть остов, суммарный вес рёбер которого
280является минимальным.
281
282** Алгоритм Прима
283/Алгоритм Прима/ --- алгоритм построения минимального остовного дерева
284взвешенного связного неотрицательного графа.
285
286В данном алгоритме кратчайший остов порождается в процессе разрастания
287одного дерева, к которому присоединяются ближайшие одиночные вершины.
288Каждая одиночная вершина является деревом.
289
290На выходе мы получаем множество рёбер, которые лежат в минимальном
291остовном дереве.
292
293Описание шагов алгоритма:
2941. Изначально остов полагается состоящим из единственной вершины.
2952. Затем выбирается ребро минимального веса, исходящее из этой
296 вершины, и добавляется в минимальный остов.
2973. После этого остов содержит уже 2 вершины, и теперь ищется и
298 добавляется ребро минимального веса, имеющее один конец в одной из
299 двух выбранных вершин, а другой --- наоборот, во всех остальных,
300 кроме этих двух, и так далее.
301
302Этот процесс повторяется до тех пор, пока остов не станет содержать
303все вершины.
304
305В итоге будет построен остов, являющийся минимальным. Если грфа был
306изначально не связан, то остов найден не будет (количество выбранных
307рёбер останется меньше $n - 1$).
308
309*Сложность алгоритма:* $\mathcal{O}(n^2)$.
310
311** Алгоритм Борувки
312Работа алгоритма состоит из нескольких итераций, каждая из которых
313состоит в последовательном добавлении рёбер к остовному лесу графа, до
314тех пор, пока лес не превратится в дерево, то есть, лес, состоящий из
315одной компоненты связности.
316
317Алгоритм можно описать так:
3181. Изначально, пусть $T$ -- пустое множество рёбер (представляющее
319 собой остовный лес, в который каждая вершина входит в качестве
320 отдельного дерева).
3212. Пока $T$ не является деревом (что эквивалентно условию: пока число рёбер в
322 $T$ меньше, чем $V - 1$, где $V$ — число вершин в графе):
323 - Для каждой компоненты связности (то есть, дерева в остовном лесе)
324 в подграфе с рёбрами $T$, найдём самое дешёвое ребро, связывающее
325 эту компоненту с некоторой другой компонентой
326 связности. (Предполагается, что веса рёбер различны, или как-то
327 дополнительно упорядочены так, чтобы всегда можно было найти
328 единственное ребро с минимальным весом).
329 - Добавим все найденные рёбра в множество $T$.
3303. Полученное множество рёбер $T$ является минимальным остовным деревом входного графа.
331
332*Сложность алгоритма:* $\mathcal{O}(q \log p)$.
333
334** Матричная теорема Кирхгофа
335/Матрица Кирхгофа/ --- матрица размера $n \times n$, где $n$ ---
336количество вершин графа.
337#+begin_export latex
338\begin{displaymath}
339 B_{ij} = \left\{\begin{aligned}
340 & -1,\,\text{если вершины с номерами $i$ и $j$ смежны} \\
341 & 0,\,\text{если $i \ne j$} \\
342 & \operatorname{deg}(u_i),\,\text{если $i = j$} \\
343 \end{aligned}
344\end{displaymath}
345#+end_export
346
347Свойства матрицы Кирхгофа:
3481. Суммы элементов в каждой строке и каждом столбце матрицы равны 0.
3492. Алгебраические дополнения всех элементов матрицы равны между собой.
3503. Определитель матрицы Кирхгофа равен 0.
351
352Матричная теорема Кирхгофа: число остовных деревьев в связном графе
353$G$ порядка $n \ge 2$ равно алгебраическому дополнению любого элемента
354матрицы Кирхгофа.
355
356** Код Прюфера
357/Код Прюфера/ --- это способ взаимно однозначного кодирования помеченных
358деревьев с $n$ вершинами с помощью последовательности $n - 2$ целых
359чисел на отрезке $[1, n]$. То есть, код Прюфера --- это биекция между
360всеми остовыми деревьями полного графа и числовыми последовательности.
361
362Алгоритм построения кода Прюфера:
363
364Вход: дерево с $n$ вершинами.
365
366Выход: код Прюфера длины $n - 2$.
367
368Повторить $n - 2$ раза:
3691. Выбрать вершину $v$ --- лист дерева с наименьшим номером;
3702. Добавить номер единственного соседа $v$ в последовательность кода Прюфера;
3713. Удалить вершину $v$ из дерева.
372
373*Сложность алгоритма построения кода:* $\mathcal{O}(n\log n)$, при
374выборе вершины за $\mathcal{O}(\log n)$
375
376** Эйлеров граф
377Если граф имеет цикл, содержащий все рёбра графа ровно один раз, то
378такой цикл называется /эйлеровым циклом/, а граф называется /эйлеровым
379графом/.
380
381Эйлеров цикл содержит не только все рёбра (по одному разу), но и все
382вершины графа (возможно несколько раз). Эйлоровым может быть только
383связный граф.
384
385Теорема: если граф $G$ связан и нетривиален, то следующие утверждения
386эквивалентны:
3871. $G$ --- эйлоров граф.
3882. Каждая вершина графа $G$ имеет чётную степень.
3893. Множество рёбер $G$ можно разбить на простые циклы.
390
391Значит для проверки наличия эйлорова цикла в графе достаточно
392убедиться, что степени всех вершин чётны.
393
394** Гамильтонов граф
395Если граф имеет простой цикл, содержащий все вершины графа (по одному
396разу), то такой цикл называется /гамильтоновым циклом/, а граф
397называется /гамильтоновым графом/.
398
399Гамильтонов цикл не обязательно содержит все рёбра графа.
400Гамильтоновым может быть только связный грай.
401
402Теорема: если $\delta(G) \ge p/2$, то граф $G$ является гамильтоновым.
403
404** Задача коммивояжёра
405Задача коммивояжёра --- задача, в которой коммивояжёр должен посетит
406$N$ городов, побывав в каждом из них ровно по одному разу и завершив
407путешествие в том городе, с которого он начал. При этом каждая
408вершина должна быть посещена только один раз.
409
410/Задача коммивояжёра/ --- задача поиска кратчайшего гамильтонова цикла в
411нагруженном полном графе.
412
413Задачу можно представить в виде /целевой функции/.
414
415Пусть $1, p_1, p_2, \ldots, p_{n - 1}, 1$ --- номера городов,
416записанные в порядке их обхода. То есть $p_k$ --- номер города,
417посещаемого на $k\text{-ом}$ шаге, $k \in \{0,\ldots, n\}, p_0 = p_n = 1$.
418Тогда пройденное расстояние можно представить в виде целевой функции:
419
420\begin{displaymath}
421 \sum_{k=0}^{n-1}c[p_k][p_{k+1}]
422\end{displaymath}
423
424Среди чисел $p_1, p_2,\ldots,p_{n-1}$ по одному разу встречается
425каждое число из интервала $2..n$. Таким образом задача коммивояжёра
426состоит в поиске перестановки чисел от $2$ до $n$, при которой целевая
427функция минимальна.
428
429* Реализация
430Граф в основном хранится в матрицах смежности, весов/цен и пропускной
431способности, но для удобства и визуализации в его структуре имеются и
432дополнительные поля:
433#+begin_src c
434typedef struct graph {
435 enum graph_type type;
436 size_t vertex_count;
437 gsl_matrix *adjecency_matrix;
438 gsl_matrix *weight_matrix;
439 gsl_matrix *capacity_matrix;
440 struct edges highlighted_edges;
441} *GRAPH;
442#+end_src
443
444** Формирование графа
445Формирование графа в соответствии с распределением осуществляется с
446помощью функции ~generate_graph~, принимающей на вход указатель на
447структуру графа, которую следует заполнить, указатель на структуру
448распределения, количество вершин и тип графа. Функция, заполняя граф
449по указателю, ничего не возвращает.
450#+begin_src c
451void
452generate_graph (GRAPH g, DISTRIBUTION dist,
453 size_t vertex_count, enum graph_type type)
454{
455 g->vertex_count = vertex_count;
456 g->type = type;
457
458 size_t n = vertex_count;
459 size_t m = MIN (n*3/2, (n*n - n)/2);
460
461 g -> adjecency_matrix = ALLOC_SQUARE_GSL_MATRIX(n);
462 g -> weight_matrix = ALLOC_SQUARE_GSL_MATRIX(n);
463 g -> capacity_matrix = ALLOC_SQUARE_GSL_MATRIX(n);
464
465 for (size_t k = 0; k < m || !is_graph_connected (g); ++k) {
466 size_t r = floor (n*n*distribution_nrand (dist)) + 1;
467 ssize_t i = floor ((r - 1)/(double) n);
468 ssize_t j = (r - 1) % n;
469
470 if (i < j && !gsl_matrix_get (g->adjecency_matrix, i, j)) {
471 double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1;
472 if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2)
473 weight = -weight;
474 double capacity = floor (MAX_CAPACITY*distribution_nrand (dist));
475 gsl_matrix_set (g -> adjecency_matrix, i, j, 1);
476 gsl_matrix_set (g -> weight_matrix, i, j, weight);
477 gsl_matrix_set (g -> capacity_matrix, i, j, capacity);
478 } else m += 1;
479 }
480}
481#+end_src
482
483** Обновление модели расстановки вершин
484Функция считывает данные из глобальной переменной графа и обновляет
485позиции также в глобальном массиве, на основе получившихся сил
486воздействия на данные вершины. Функции ничего не получает и не
487возвращает, так как работает с глобальным состоянием.
488#+begin_src c
489static inline void
490progress_model (void)
491{
492 size_t n = g.vertex_count;
493 Vector2 force_on_vertices[MAX_VERTEX_COUNT] = {0};
494 for (size_t i = 0; i < n; ++i) {
495 for (size_t j = 0; j < n; ++j) {
496 if (i == j)
497 continue;
498 Vector2 dir = Vector2Normalize (Vector2Subtract (model_vertices[j],
499 model_vertices[i]));
500 if (gsl_matrix_get (g.adjecency_matrix, i, j) ||
501 gsl_matrix_get (g.adjecency_matrix, j, i)) {
502 float distance = Vector2Distance (model_vertices[i],
503 model_vertices[j]);
504 float mag = MODEL_C_SPRING*logf (distance/MODEL_L);
505 force_on_vertices[i] = Vector2Add (force_on_vertices[i],
506 Vector2Scale (dir, mag));
507 } else {
508 float square_distance = Vector2DistanceSqr (model_vertices[j],
509 model_vertices[i]);
510 float mag = MODEL_C_REP/square_distance;
511 force_on_vertices[i] = Vector2Add (force_on_vertices[i],
512 Vector2Scale (dir, -mag));
513 }
514 }
515 }
516
517 float heat = exp ((-1 + MODEL_COOLING_FACTOR)*(GetTime () - start_time))/100;
518 for (int i = 0; i < n; ++i) {
519 model_vertices[i] = Vector2Add (model_vertices[i],
520 Vector2Scale (force_on_vertices[i], heat));
521 }
522}
523#+end_src
524
525** Поиск экстремальных путей методом Шимбелла
526Функция принимает указатель на структуру графа, количество ребер
527маршрута и выбор из поиска кратчайших или длиннейших маршрутов, и
528возвращает полученную матрицу Шимбелла.
529#+begin_src c
530gsl_matrix *
531shimbell_method (GRAPH g, size_t edge_count, bool max)
532{
533 size_t n = g->vertex_count;
534 gsl_matrix *adj = g->adjecency_matrix;
535 gsl_matrix *shimbell = ALLOC_SQUARE_GSL_MATRIX (n);
536
537 gsl_matrix_memcpy (shimbell, adj);
538 if (n == 1)
539 return shimbell;
540
541 gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX (n);
542 for (size_t l = 0; l < n - 1; ++l) {
543 gsl_matrix_memcpy (tmp, shimbell);
544 for (size_t i = 0; i < n; ++i) {
545 for (size_t j = 0; j < n; ++j) {
546 double bestval = max ? 0 : INFINITY;
547 for (size_t k = 0; k < n; ++k) {
548 double a = gsl_matrix_get (tmp, k, j);
549 double b = gsl_matrix_get (adj, i, k);
550 if (a == 0 || b == 0)
551 continue;
552 double val = a + b;
553 if (max ? val > bestval
554 : val < bestval) {
555 bestval = val;
556 }
557 } gsl_matrix_set (shimbell, i, j, bestval);
558 }
559 }
560 } gsl_matrix_free (tmp);
561
562 return shimbell;
563}
564#+end_src
565
566** Определение возможности построения маршрута
567Функция получает указатель на структуру матрицы и индексы двух вершин,
568возвращая признак возможности построения пути между этими вершинами.
569По сути функция выполняет проход в глубину, за счет использования
570стека.
571#+begin_src c
572bool
573are_vertices_connected (gsl_matrix *m, size_t from, size_t to)
574{
575 size_t n = m->size1;
576 struct stack {
577 size_t *items;
578 size_t count;
579 size_t capacity;
580 };
581
582 struct stack stack = {0};
583 DYNAMIC_ARRAY_ENSURE_CAPACITY (stack, n);
584 DYNAMIC_ARRAY_APPEND (stack, from);
585 while (stack.count) {
586 size_t vertex = stack.items[stack.count - 1];
587 stack.count -= 1;
588 for (size_t i = 0; i < n; ++i) {
589 if (gsl_matrix_get (m, vertex, i)) {
590 if (to == i) return true;
591 DYNAMIC_ARRAY_APPEND (stack, i);
592 }
593 }
594 } return false;
595}
596#+end_src
597
598** Поиск количества путей между двумя вершинами
599Функция получает указатель на структуру графа и индексы двух вершин и
600возвращает количество путей между ними. Постепенно возводя матрицу
601смежности в степень $n - 2$ и на каждом шагу аккумулируя значение на
602матрица с указанными индексами получаем количество путей между ними.
603#+begin_src c
604size_t
605graph_count_routes (GRAPH g, size_t from, size_t to)
606{
607 size_t n = g->vertex_count;
608 gsl_matrix *adj = g->adjecency_matrix;
609 gsl_matrix *con = ALLOC_SQUARE_GSL_MATRIX(n);
610 gsl_matrix *pow = ALLOC_SQUARE_GSL_MATRIX(n);
611 gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX(n);
612
613 for (size_t e = 0; e < n*n; ++e)
614 con->data[e] = adj->data[e] != 0 ? 1 : 0;
615 gsl_matrix_memcpy (pow, con);
616 gsl_matrix_memcpy (tmp, con);
617
618 size_t count = gsl_matrix_get (pow, from, to);
619 for (size_t k = 0; k < n - 2; ++k) {
620 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
621 1.0, tmp, con,
622 0.0, pow);
623 count += gsl_matrix_get (pow, from, to);
624 gsl_matrix *swap = tmp;
625 tmp = pow;
626 pow = swap;
627 }
628
629 gsl_matrix_free (con);
630 gsl_matrix_free (tmp);
631 gsl_matrix_free (pow);
632
633 return count;
634}
635#+end_src
636
637** Алгоритм Дейкстры
638Функция получает указатель на структуру графа и индексы двух вершин и
639переключатель между поиском кратчайшего и длиннейшего пути, хотя
640алгоритм Дейкстры может и не найти самый длиннейший путь. Функция
641возвращает путь в виде массива вершин.
642#+begin_src c
643size_t *
644dijkstra_positive (GRAPH g, size_t from, size_t to, bool max)
645{
646 struct dijkstra_node {
647 double distance;
648 size_t previous;
649 bool visited;
650 };
651
652 size_t n = g->vertex_count;
653
654 double cost[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT];
655 for (size_t i = 0; i < n; ++i) {
656 for (size_t j = 0; j < n; ++j) {
657 double val = gsl_matrix_get (g->weight_matrix, i, j);
658 if (val == 0)
659 cost[i][j] = max ? -INFINITY : INFINITY;
660 else
661 cost[i][j] = val;
662 }
663 }
664
665 struct dijkstra_node nodes[MAX_VERTEX_COUNT];
666 for (size_t i = 0; i < n; ++i) {
667 nodes[i] = (struct dijkstra_node) {
668 .distance = cost[from][i],
669 .previous = from,
670 .visited = false,
671 };
672 }
673 nodes[from].distance = 0;
674 nodes[from].visited = true;
675
676 for (size_t count = 1; count < n - 1; ++count) {
677 size_t next;
678 double best_distance = max ? -INFINITY : INFINITY;
679 for (size_t i = 0; i < n; i++) {
680 if ((max ? nodes[i].distance > best_distance
681 : nodes[i].distance < best_distance)
682 && !nodes[i].visited) {
683 best_distance = nodes[i].distance;
684 next = i;
685 }
686 }
687
688 nodes[next].visited = true;
689 for (size_t i = 0; i < n; ++i) {
690 if (!nodes[i].visited) {
691 double distance = best_distance + cost[next][i];
692 if ((max ? distance > nodes[i].distance
693 : distance < nodes[i].distance)) {
694 nodes[i].distance = distance;
695 nodes[i].previous = next;
696 }
697 }
698 }
699 }
700
701 if (nodes[to].distance == (max ? -INFINITY : INFINITY))
702 return NULL;
703
704 size_t len = 1;
705 for (size_t i = to; i != from; i = nodes[i].previous)
706 len += 1;
707
708 size_t *path = malloc ((len + 1)*sizeof (*path));
709 size_t v = len;
710 path[v--] = n;
711 for (size_t i = to; i != from; i = nodes[i].previous)
712 path[v--] = i;
713 path[v] = from;
714
715 return path;
716}
717#+end_src
718
719** Алгоритм Флойда-Уоршелла
720Функция получает указатель на структуру графа и индексы двух вершин и
721переключатель между поиском кратчайшего и длиннейшего пути. Функция
722возвращает путь в виде массива вершин.
723#+begin_src c
724size_t *
725floyd_warshall (GRAPH g, size_t from, size_t to, bool max)
726{
727 const size_t n = g->vertex_count;
728 double dist[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT];
729 size_t next[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT];
730
731 // initialize dist and next
732 for (size_t u = 0; u < n; ++u) {
733 for (size_t v = 0; v < n; ++v) {
734 if (gsl_matrix_get (g->weight_matrix, u, v) == 0) {
735 dist[u][v] = max ? -INFINITY : INFINITY;
736 next[u][v] = n;
737 } else {
738 dist[u][v] = gsl_matrix_get (g->weight_matrix, u, v);
739 next[u][v] = v;
740 }
741 dist[v][v] = 0;
742 next[v][v] = v;
743 }
744 }
745
746 // compute dist and next
747 for (size_t k = 0; k < n; ++k) {
748 for (size_t i = 0; i < n; ++i) {
749 for (size_t j = 0; j < n; ++j) {
750 if (max ? dist[i][j] < dist[i][k] + dist[k][j]
751 : dist[i][j] > dist[i][k] + dist[k][j]) {
752 dist[i][j] = dist[i][k] + dist[k][j];
753 next[i][j] = next[i][k];
754 }
755 }
756 }
757 }
758
759 puts ("DISTANCE MATRIX:");
760 printf (" ");
761 for (size_t j = 0; j < n; j++)
762 printf (" [%zu]", j);
763 putchar ('\n');
764 for (size_t i = 0; i < n; i++) {
765 printf ("[%zu]", i);
766 for (size_t j = 0; j < n; j++)
767 printf ("%4g", dist[i][j]);
768 putchar ('\n');
769 }
770
771 // build path
772 if (next[from][to] == n)
773 return NULL;
774
775 size_t len = 1;
776 for (size_t v = from; v != to; v = next[v][to])
777 len += 1;
778
779 size_t *path = malloc ((len + 1)*sizeof (*path));
780 size_t e = 0;
781 for (size_t v = from; v != to; v = next[v][to])
782 path[e++] = v;
783 path[e++] = to;
784 path[e] = n;
785
786 return path;
787}
788#+end_src
789
790** Алгоритм Форда-Фалкерсона
791Функция получает указатель на структуру графа и индексы двух вершин.
792Функция возвращает максимальные поток из первой вершины во вторую.
793#+begin_src c
794double
795max_flow_ford_fulkerson (GRAPH g, size_t source, size_t sink)
796{
797 size_t n = g->vertex_count;
798 size_t parents[MAX_VERTEX_COUNT];
799 for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i)
800 parents[i] = n;
801
802 gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n);
803 gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix);
804 double max_flow = 0;
805
806 struct stack {
807 size_t *items;
808 size_t count;
809 size_t capacity;
810 };
811
812 DYNAMIC_ARRAY_RESET (g->highlighted_edges);
813 struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n);
814 struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n);
815 struct stack *front_stack = &stack1;
816 struct stack *back_stack = &stack2;
817 for (;;) {
818 bool visited[MAX_VERTEX_COUNT] = { false };
819 DYNAMIC_ARRAY_RESET (*front_stack);
820 DYNAMIC_ARRAY_APPEND (*front_stack, source);
821 visited[source] = true;
822 while (front_stack->count) {
823 DYNAMIC_ARRAY_RESET (*back_stack);
824 DYNAMIC_ARRAY_FOREACH (v, *front_stack) {
825 size_t vertex = *v;
826 for (size_t i = 0; i < n; ++i) {
827 if (!visited[i] &&
828 gsl_matrix_get (residual_capacity_matrix, vertex, i) > 0) {
829 parents[i] = vertex;
830 if (sink == i) goto found;
831 DYNAMIC_ARRAY_APPEND (*back_stack, i);
832 visited[i] = true;
833 }
834 }
835 } SWAP(front_stack, back_stack);
836 }
837 break;
838
839 found: {
840 double path_flow = INFINITY;
841 for (size_t v = sink; v != source; v = parents[v]) {
842 size_t u = parents[v];
843 DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v}));
844 path_flow = fmin (path_flow, gsl_matrix_get (residual_capacity_matrix,
845 u, v));
846 }
847
848 for (size_t v = sink; v != source; v = parents[v]) {
849 size_t u = parents[v];
850 ,*gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow;
851 ,*gsl_matrix_ptr (residual_capacity_matrix, v, u) += path_flow;
852 }
853
854 max_flow += path_flow;
855 }
856 }
857
858 gsl_matrix_free (residual_capacity_matrix);
859
860 return max_flow;
861}
862#+end_src
863
864** Нахождение потока минимальной стоимости
865Функция получает указатель на структуру графа, индексы двух вершин и
866требуемый поток. Функция возвращает минимальную цену данного потока.
867#+begin_src c
868double
869min_cost_flow (GRAPH g, size_t s, size_t t, double required_flow)
870{
871 size_t n = g->vertex_count;
872 gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n);
873 gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix);
874 gsl_matrix *residual_cost_matrix = gsl_matrix_alloc (n, n);
875 gsl_matrix_memcpy (residual_cost_matrix, g->weight_matrix);
876 gsl_matrix *result_flow_matrix = gsl_matrix_calloc (n, n);
877 double costs[MAX_VERTEX_COUNT];
878 size_t parents[MAX_VERTEX_COUNT];
879 double flow;
880 double min_cost;
881
882 DYNAMIC_ARRAY_RESET (g->highlighted_edges);
883 while (flow < required_flow) {
884 // Bellman-Ford
885 for (size_t i = 0; i < n; ++i) {
886 costs[i] = INFINITY;
887 parents[i] = n;
888 } costs[s] = 0;
889 for (size_t i = 0; i < n - 1; ++i) {
890 for (size_t u = 0; u < n; ++u) {
891 for (size_t v = 0; v < n; ++v) {
892 if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue;
893 double cost = gsl_matrix_get (residual_cost_matrix, u, v);
894 if (costs[u] != INFINITY &&
895 cost != INFINITY &&
896 costs[u] + cost < costs[v]) {
897 costs[v] = costs[u] + cost;
898 parents[v] = u;
899 }
900 }
901 }
902 }
903
904 // If no path
905 if (parents[t] == n) return NAN;
906
907 // Find max flow
908 double path_flow = INFINITY;
909 for (size_t v = t; v != s; v = parents[v]) {
910 size_t u = parents[v];
911 path_flow = fmin (path_flow,
912 gsl_matrix_get (residual_capacity_matrix, u, v));
913 }
914
915 // Apply flow constraint
916 path_flow = fmin (path_flow, required_flow - flow);
917
918 // Update costs and capacities
919 for (int v = t; v != s; v = parents[v]) {
920 int u = parents[v];
921 DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v}));
922 *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow;
923 *gsl_matrix_ptr (result_flow_matrix, u, v) += path_flow;
924 min_cost += path_flow*gsl_matrix_get (residual_cost_matrix, u, v);
925
926 if (!gsl_matrix_get (residual_capacity_matrix, u, v))
927 gsl_matrix_set (residual_cost_matrix, u, v, INFINITY);
928 }
929
930 flow += path_flow;
931 }
932
933 gsl_matrix_free (residual_capacity_matrix);
934 gsl_matrix_free (residual_cost_matrix);
935 gsl_matrix_free (result_flow_matrix);
936
937 return min_cost;
938}
939#+end_src
940
941** Нахождение количества остовов
942Функция получает указатель на структуру графа, и возвращает количество
943остов графа, применяя матрицу Кирхгофа.
944#+begin_src c
945size_t
946count_spanning_trees (GRAPH g)
947{
948 size_t n = g->vertex_count;
949 gsl_matrix *kirchhoff_matrix = gsl_matrix_calloc (n, n);
950
951 for (size_t i = 0; i < n; i++) {
952 for (size_t j = i; j < n; j++) {
953 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
954 gsl_matrix_get (g->adjecency_matrix, j, i)) {
955 *gsl_matrix_ptr (kirchhoff_matrix, i, i) += 1;
956 *gsl_matrix_ptr (kirchhoff_matrix, j, j) += 1;
957 *gsl_matrix_ptr (kirchhoff_matrix, i, j) = -1;
958 *gsl_matrix_ptr (kirchhoff_matrix, j, i) = -1;
959 }
960 }
961 }
962
963 size_t count = gsl_matrix_cofactor (kirchhoff_matrix, 0, 0);
964 gsl_matrix_free (kirchhoff_matrix);
965
966 return count;
967}
968#+end_src
969
970** Нахождение минимального остова алгоритмом Прима
971Функция получает указатель на структуру графа, и возвращает матрицу
972весов минимального остова.
973#+begin_src c
974gsl_matrix *
975min_weight_spannig_tree_prim (GRAPH g)
976{
977 size_t count = 0;
978 double total_weight = 0;
979 size_t n = g->vertex_count;
980 gsl_matrix *remaining_graph = gsl_matrix_alloc (n, n);
981
982 for (size_t i = 0; i < n; ++i) {
983 for (int j = 0; j < n; ++j) {
984 double weight = gsl_matrix_get (g->weight_matrix, i, j);
985 gsl_matrix_set (remaining_graph, i, j, weight == 0 ? INFINITY : weight);
986 }
987 }
988
989 gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n);
990 bool visited[MAX_VERTEX_COUNT] = {0};
991 size_t spanning_tree_vertex_count = 0;
992 while (spanning_tree_vertex_count < g->vertex_count) {
993 double minimum_weight = INFINITY;
994 size_t a;
995 size_t b;
996 for (size_t i = 0 ; i < n; ++i) {
997 for (size_t j = 0; j < n; ++j) {
998 count += 1;
999 double weight = gsl_matrix_get (remaining_graph, i, j);
1000 if (weight < minimum_weight &&
1001 ((visited[i] != visited[j]) ||
1002 spanning_tree_vertex_count == 0)) {
1003 minimum_weight = weight;
1004 a = i;
1005 b = j;
1006 }
1007 }
1008 }
1009
1010 if (!visited[a] || !visited[b]) {
1011 if (!visited[a]) {
1012 spanning_tree_vertex_count += 1;
1013 visited[a] = true;
1014 }
1015
1016 if (!visited[b]) {
1017 spanning_tree_vertex_count += 1;
1018 visited[b] = true;
1019 }
1020
1021 total_weight += minimum_weight;
1022 }
1023
1024 gsl_matrix_set (remaining_graph, a, b, INFINITY);
1025 gsl_matrix_set (remaining_graph, b, a, INFINITY);
1026 gsl_matrix_set (spanning_tree, a, b, minimum_weight);
1027 gsl_matrix_set (spanning_tree, b, a, minimum_weight);
1028 printf ("%zu %zu = %f\n", a, b, minimum_weight);
1029 } gsl_matrix_free (remaining_graph);
1030
1031 return spanning_tree;
1032}
1033#+end_src
1034
1035** Нахождение минимального остова алгоритмом Борувки
1036Функция получает указатель на структуру графа, и возвращает матрицу
1037весов минимального остова.
1038#+begin_src c
1039gsl_matrix *
1040min_weight_spannig_tree_boruvka (GRAPH g)
1041{
1042 size_t n = g->vertex_count;
1043 gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n);
1044
1045 struct edge_weight {
1046 size_t from;
1047 size_t to;
1048 double weight;
1049 };
1050
1051 size_t number_of_components = g->vertex_count;
1052 struct edge_weight lightest_edges[MAX_VERTEX_COUNT];
1053 size_t parent_components[MAX_VERTEX_COUNT];
1054 size_t next_components[MAX_VERTEX_COUNT];
1055
1056 for (size_t i = 0; i < n; ++i)
1057 parent_components[i] = i;
1058
1059 size_t count = 0;
1060 double min_weight = 0;
1061 while (number_of_components > 1) {
1062 for (size_t i = 0; i < n; ++i)
1063 lightest_edges[i] = (struct edge_weight) { 0, 0, .weight = INFINITY };
1064
1065 for (size_t u = 0; u < n; ++u) {
1066 for (size_t v = 0; v < n; ++v) {
1067 if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue;
1068 count += 1;
1069 double weight =
1070 gsl_matrix_get (g->weight_matrix, u, v) +
1071 gsl_matrix_get (g->weight_matrix, v, u);
1072
1073 if (parent_components[u] != parent_components[v]) {
1074 if (lightest_edges[parent_components[u]].weight > weight) {
1075 lightest_edges[parent_components[u]].weight = weight;
1076 lightest_edges[parent_components[u]].from = u;
1077 lightest_edges[parent_components[u]].to = v;
1078 }
1079 if (lightest_edges[parent_components[v]].weight > weight) {
1080 lightest_edges[parent_components[v]].weight = weight;
1081 lightest_edges[parent_components[v]].from = u;
1082 lightest_edges[parent_components[v]].to = v;
1083 }
1084 }
1085 }
1086 }
1087
1088 // Adding selected edges and combining components
1089 for (size_t i = 0; i < number_of_components; ++i) {
1090 count++;
1091
1092 double weight = lightest_edges[i].weight;
1093 size_t u = lightest_edges[i].from;
1094 size_t v = lightest_edges[i].to;
1095
1096 if (weight == INFINITY) continue;
1097
1098 if (!gsl_matrix_get (spanning_tree, u, v)) {
1099 min_weight += weight;
1100 gsl_matrix_set (spanning_tree, u, v, weight);
1101 gsl_matrix_set (spanning_tree, v, u, weight);
1102 }
1103
1104 // Do the join
1105 if (parent_components[u] != parent_components[v]) {
1106 number_of_components -= 1;
1107 size_t component_to_remove = parent_components[v];
1108 for (size_t j = 0; j < n; j++) {
1109 if (parent_components[j] == component_to_remove) {
1110 parent_components[j] = parent_components[u];
1111 }
1112 }
1113 }
1114 }
1115 }
1116
1117 return spanning_tree;
1118}
1119#+end_src
1120
1121** Код Прьюфера
1122Функция получает указатель на структуру матрицы весов остова, и
1123проверяет, сможет ли она закодировать и декодировать кодом Прьюфера.
1124Функция ничего не возвращает, а сразу всё печатает.
1125#+begin_src c
1126void
1127prufer_code (gsl_matrix *spanning_tree_matrix)
1128{
1129 size_t n = spanning_tree_matrix->size1;
1130
1131 gsl_matrix *tree = gsl_matrix_alloc (n, n);
1132 gsl_matrix_memcpy (tree, spanning_tree_matrix);
1133 struct {
1134 size_t *items;
1135 size_t count;
1136 size_t capacity;
1137 } prufer = {0};
1138 struct {
1139 size_t *items;
1140 size_t count;
1141 size_t capacity;
1142 } weights = {0};
1143
1144 for (size_t i = 0; i < n - 1; ++i) {
1145 // Find hanging vertex with the lowest number
1146 size_t v, u;
1147 for (size_t j = 0; j < n; ++j) {
1148 size_t deg = 0;
1149 for (size_t k = 0; k < n; ++k) {
1150 if (gsl_matrix_get (tree, j, k) > 0) {
1151 deg += 1;
1152 u = k;
1153 }
1154 }
1155
1156 if (deg == 1) {
1157 v = j;
1158 break;
1159 }
1160 }
1161
1162 // Encode the only vertex neighbouring `v'
1163 DYNAMIC_ARRAY_APPEND (prufer, u);
1164 DYNAMIC_ARRAY_APPEND (weights, gsl_matrix_get (tree, u, v));
1165
1166 // "Pop"
1167 gsl_matrix_set (tree, u, v, 0);
1168 gsl_matrix_set (tree, v, u, 0);
1169 }
1170
1171 printf ("MINIMAL_SPANNING_TREE:\n");
1172 print_gsl_matrix (spanning_tree_matrix);
1173
1174 printf ("PRUFER_CODE: ");
1175 DYNAMIC_ARRAY_FOREACH (p, prufer)
1176 printf ("%zu ", *p);
1177 printf ("\n");
1178
1179 printf ("SAVED_WEIGHTS: ");
1180 DYNAMIC_ARRAY_FOREACH (w, weights)
1181 printf ("%zu ", *w);
1182 printf ("\n");
1183
1184 // Decoding
1185 gsl_matrix *decoded_tree = gsl_matrix_calloc (n, n);
1186
1187 struct {
1188 size_t *items;
1189 size_t count;
1190 size_t capacity;
1191 } not_used_vertices = {0};
1192 for (size_t i = 0; i < n; ++i)
1193 DYNAMIC_ARRAY_APPEND (not_used_vertices, i);
1194
1195 for (size_t i = 0; i < n - 1; ++i) {
1196 // Picking unused vertex v with the lowest number not in the rest
1197 // of the Prufer code
1198 size_t v;
1199 for (size_t j = 0; j < not_used_vertices.count; ++j) {
1200 bool met = false;
1201 for (size_t k = i; k < n - 1; ++k) {
1202 if (not_used_vertices.items[j] == prufer.items[k]) {
1203 met = true;
1204 break;
1205 }
1206 }
1207
1208 if (!met) {
1209 v = not_used_vertices.items[j];
1210
1211 // Remove now used
1212 DYNAMIC_ARRAY_ERASE (not_used_vertices, j);
1213 break;
1214 }
1215 }
1216
1217 // Add edge
1218 gsl_matrix_set (decoded_tree, v, prufer.items[i], weights.items[i]);
1219 gsl_matrix_set (decoded_tree, prufer.items[i], v, weights.items[i]);
1220 }
1221
1222 printf ("DECODED_MINIMAL_SPANNING_TREE:\n");
1223 print_gsl_matrix (decoded_tree);
1224
1225 for (size_t i = 0; i < n; ++i) {
1226 for (size_t j = 0; j < n; ++j) {
1227 if (gsl_matrix_get (spanning_tree_matrix, i, j) !=
1228 gsl_matrix_get (decoded_tree, i, j)) {
1229 printf ("Error, matrices are not the same!\n");
1230 return;
1231 }
1232 }
1233 }
1234 printf("Success, matrices the same!\n");
1235
1236 gsl_matrix_free (tree);
1237 gsl_matrix_free (decoded_tree);
1238}
1239#+end_src
1240
1241** Алгоритм определения Эйлерова графа
1242Функция получает указатель на структуру графа, и возвращает признак,
1243является ли данный граф Эйлеровым.
1244#+begin_src c
1245bool
1246is_graph_eulerian (GRAPH g)
1247{
1248 size_t n = g->vertex_count;
1249
1250 if (n <= 2)
1251 return false;
1252
1253 // Check if degree of all vertices is even
1254 for (size_t i = 0; i < n; ++i) {
1255 size_t degree = 0;
1256 for (size_t j = 0; j < n; ++j) {
1257 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1258 gsl_matrix_get (g->adjecency_matrix, j, i))
1259 degree += 1;
1260 }
1261
1262 if (degree % 2 != 0)
1263 return false;
1264 }
1265
1266 return true;
1267}
1268#+end_src
1269
1270** Алгоритм определения Гамильтонова графа
1271Функция получает указатель на структуру графа, и возвращает признак,
1272является ли данный граф Гамильтоновым.
1273#+begin_src c
1274bool
1275is_graph_hamiltonian (GRAPH g)
1276{
1277 size_t n = g->vertex_count;
1278
1279 // Find neighbours
1280 struct {
1281 size_t *items;
1282 size_t count;
1283 size_t capacity;
1284 } neighbours[MAX_VERTEX_COUNT] = {0};
1285 for (size_t i = 0; i < n; ++i) {
1286 for (size_t j = 0; j < n; ++j) {
1287 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1288 gsl_matrix_get (g->adjecency_matrix, j, i)) {
1289 DYNAMIC_ARRAY_APPEND (neighbours[i], j);
1290 }
1291 }
1292 }
1293
1294 struct {
1295 size_t *items;
1296 size_t count;
1297 size_t capacity;
1298 } not_visited_neighbours[MAX_VERTEX_COUNT] = {0};
1299
1300 struct {
1301 size_t *items;
1302 size_t count;
1303 size_t capacity;
1304 } path = {0};
1305
1306 size_t a = 0;
1307 DYNAMIC_ARRAY_APPEND (path, a);
1308 DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[a], neighbours[a]);
1309
1310 while (path.count) {
1311 size_t x = path.items[path.count - 1];
1312
1313 if (not_visited_neighbours[x].count) {
1314 size_t y = not_visited_neighbours[x].items[not_visited_neighbours[x].count - 1];
1315 not_visited_neighbours[x].count -= 1;
1316
1317 bool y_in_path = false;
1318 DYNAMIC_ARRAY_FOREACH(p, path) {
1319 if (*p == y) {
1320 y_in_path = true;
1321 break;
1322 }
1323 }
1324
1325 if (!y_in_path) {
1326 DYNAMIC_ARRAY_APPEND (path, y);
1327 DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[y], neighbours[y]);
1328 if (path.count == n &&
1329 (gsl_matrix_get (g->adjecency_matrix, a, y) ||
1330 gsl_matrix_get (g->adjecency_matrix, y, a))) {
1331 return true;
1332 }
1333 }
1334 } else {
1335 path.count -= 1; // pop back
1336 }
1337 }
1338
1339 return false;
1340}
1341#+end_src
1342
1343** Алгоритм обеспечения Эйлерова графа
1344Функция получает указатель на структуру графа, и добавляет и убирает
1345вершины пока граф не становится Эйлеровым. Функция ничего не
1346возвращает.
1347#+begin_src c
1348void
1349graph_ensure_eulerian (GRAPH g)
1350{
1351 size_t n = g->vertex_count;
1352
1353 if (n <= 2) {
1354 printf ("Not enough vertices for an Euler cycle (<3)\n");
1355 return;
1356 }
1357
1358 if (is_graph_eulerian (g)) {
1359 printf ("Graph is Eulerian, no modifications needed\n");
1360 } else {
1361 // Find vertices with odd degrees
1362 struct {
1363 size_t *items;
1364 size_t count;
1365 size_t capacity;
1366 } odd_degree_vertices = {0};
1367 for (size_t i = 0; i < n; ++i) {
1368 size_t degree = 0;
1369 for (size_t j = 0; j < n; ++j) {
1370 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1371 gsl_matrix_get (g->adjecency_matrix, j, i))
1372 degree += 1;
1373 }
1374 if (degree % 2 != 0)
1375 DYNAMIC_ARRAY_APPEND (odd_degree_vertices, i);
1376 }
1377
1378 size_t first;
1379
1380 // Join vertices with odd degrees
1381 add_edge:
1382 if (odd_degree_vertices.count)
1383 first = odd_degree_vertices.items[0];
1384
1385 // Find pair
1386 for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) {
1387 size_t second = odd_degree_vertices.items[second_index];
1388
1389 // Help keep acyclic
1390 size_t i = first < second ? first : second;
1391 size_t j = first > second ? first : second;
1392
1393 // Add edge if there isn't
1394 if (gsl_matrix_get (g->adjecency_matrix, i, j) == 0 &&
1395 gsl_matrix_get (g->adjecency_matrix, j, i) == 0) {
1396 double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1;
1397 double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1;
1398 graph_edge_set (g, i, j, new_weight, new_capacity);
1399
1400 // Update
1401 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index);
1402 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0);
1403
1404 goto add_edge;
1405 }
1406 }
1407
1408 // If edge addition helped only partially, delete edges
1409 remove_edge:
1410 if (odd_degree_vertices.count)
1411 first = odd_degree_vertices.items[0];
1412
1413 for (size_t second_index = 1;
1414 second_index < odd_degree_vertices.count; ++second_index) {
1415 size_t second = odd_degree_vertices.items[second_index];
1416
1417 size_t i = first < second ? first : second;
1418 size_t j = first > second ? first : second;
1419
1420 // Don't delete edge if it will make graph unconnected
1421 size_t degree_i = 0;
1422 size_t degree_j = 0;
1423 for (size_t k = 0; k < n; ++k) {
1424 if (gsl_matrix_get (g->adjecency_matrix, i, k) ||
1425 gsl_matrix_get (g->adjecency_matrix, k, i))
1426 degree_i += 1;
1427 if (gsl_matrix_get (g->adjecency_matrix, j, k) ||
1428 gsl_matrix_get (g->adjecency_matrix, k, j))
1429 degree_j += 1;
1430 }
1431
1432 if (degree_i == 1 &&
1433 degree_j == 1)
1434 continue;
1435
1436 gsl_matrix_set (g -> adjecency_matrix, i, j, 0);
1437 gsl_matrix_set (g -> weight_matrix, i, j, 0);
1438 gsl_matrix_set (g -> capacity_matrix, i, j, 0);
1439 gsl_matrix_set (g -> adjecency_matrix, j, i, 0);
1440 gsl_matrix_set (g -> weight_matrix, j, i, 0);
1441 gsl_matrix_set (g -> capacity_matrix, j, i, 0);
1442
1443 // Update
1444 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index);
1445 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0);
1446
1447 goto remove_edge;
1448 }
1449
1450 if (odd_degree_vertices.count)
1451 printf ("Unable to make graph Eulerian\n");
1452
1453 printf ("ADJECENCY_MATRIX:\n");
1454 print_gsl_matrix (g->adjecency_matrix);
1455 }
1456
1457 // Find Euler cycles
1458
1459 // Find neighbours
1460 struct {
1461 size_t *items;
1462 size_t count;
1463 size_t capacity;
1464 } neighbours[MAX_VERTEX_COUNT] = {0};
1465 for (size_t i = 0; i < n; ++i) {
1466 for (size_t j = 0; j < n; ++j) {
1467 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1468 gsl_matrix_get (g->adjecency_matrix, j, i)) {
1469 DYNAMIC_ARRAY_APPEND (neighbours[i], j);
1470 }
1471 }
1472 }
1473
1474 struct {
1475 size_t *items;
1476 size_t count;
1477 size_t capacity;
1478 } euler_cycle = {0};
1479 struct {
1480 size_t *items;
1481 size_t count;
1482 size_t capacity;
1483 } s = {0};
1484 DYNAMIC_ARRAY_APPEND (s, 0);
1485
1486 while (s.count) {
1487 size_t v = s.items[s.count - 1];
1488
1489 if (!neighbours[v].count) {
1490 s.count -= 1;
1491 DYNAMIC_ARRAY_APPEND (euler_cycle, v);
1492 } else {
1493 size_t u = neighbours[v].items[0];
1494 DYNAMIC_ARRAY_APPEND (s, u);
1495
1496 // Removing
1497 DYNAMIC_ARRAY_ERASE (neighbours[v], 0);
1498 for (size_t i = 0; i < neighbours[u].count; ++i) {
1499 if (neighbours[u].items[i] == v) {
1500 DYNAMIC_ARRAY_ERASE (neighbours[u], i);
1501 i -= 1;
1502 }
1503 }
1504 }
1505 }
1506
1507 DYNAMIC_ARRAY_APPEND (euler_cycle, n);
1508 free (g->highlighted_path);
1509 g->highlighted_path = euler_cycle.items;
1510
1511 for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i)
1512 DYNAMIC_ARRAY_FREE (neighbours[i]);
1513 DYNAMIC_ARRAY_FREE (s);
1514}
1515#+end_src
1516
1517** Алгоритм обеспечения Гамильтонова графа
1518Функция получает указатель на структуру графа, и добавляет и убирает
1519вершины пока граф не становится Гамильтоновым. Функция ничего не возвращает.
1520#+begin_src c
1521void
1522graph_ensure_hamiltonian (GRAPH g)
1523{
1524 size_t n = g->vertex_count;
1525
1526 if (n <= 2) {
1527 printf ("Not enough vertices for an Hamilton cycle (<3)\n");
1528 return;
1529 }
1530
1531 if (is_graph_hamiltonian (g)) {
1532 printf ("Graph is Hamiltonian, no modifications needed\n");
1533 } else {
1534 struct {
1535 struct vertex_degree {
1536 size_t vertex;
1537 size_t degree;
1538 } *items;
1539 size_t count;
1540 size_t capacity;
1541 } vertex_degree_pairs = {0};
1542 for (size_t i = 0; i < n; ++i) {
1543 size_t degree = 0;
1544 for (size_t j = 0; j < n; ++j) {
1545 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1546 gsl_matrix_get (g->adjecency_matrix, j, i))
1547 degree += 1;
1548 }
1549
1550 DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {i, degree}));
1551 }
1552
1553 // Add edges to vertices with low degree
1554 do {
1555 size_t min_idx = 0;
1556 for (size_t i = 1; i < n; ++i) {
1557 if (vertex_degree_pairs.items[i].degree <
1558 vertex_degree_pairs.items[min_idx].degree)
1559 min_idx = i;
1560 }
1561
1562 size_t vertex1 = vertex_degree_pairs.items[min_idx].vertex;
1563 size_t degree1 = vertex_degree_pairs.items[min_idx].degree;
1564 DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx);
1565
1566 for (size_t k = 0; k < n; ++k) {
1567 size_t min_idx = 0;
1568 for (size_t i = 1; i < n; ++i) {
1569 if (vertex_degree_pairs.items[min_idx].vertex != vertex1 &&
1570 vertex_degree_pairs.items[i].degree <
1571 vertex_degree_pairs.items[min_idx].degree)
1572 min_idx = i;
1573 }
1574 size_t vertex2 = vertex_degree_pairs.items[min_idx].vertex;
1575 size_t degree2 = vertex_degree_pairs.items[min_idx].degree;
1576
1577 if (!gsl_matrix_get (g->adjecency_matrix, vertex1, vertex2) &&
1578 !gsl_matrix_get (g->adjecency_matrix, vertex2, vertex1)) {
1579 size_t i = vertex1 < vertex2 ? vertex1 : vertex2;
1580 size_t j = vertex1 > vertex2 ? vertex1 : vertex2;
1581
1582 double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1;
1583 double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1;
1584 graph_edge_set (g, i, j, new_weight, new_capacity);
1585
1586 printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight);
1587
1588 DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx);
1589 DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex2, degree2 + 1}));
1590 break;
1591 }
1592 }
1593
1594 DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex1, degree1 + 1}));
1595 } while (!is_graph_hamiltonian(g));
1596 }
1597
1598 find_hamiltonian_cycles (g);
1599}
1600#+end_src
1601
1602** Задача коммивояжёра
1603Функция получает указатель на структуру графа, и находит все
1604Гамильтоновые циклы в нём, ограничиваясь на 20 вершин и 1000000
1605циклов, для обеспечения почти мгновенной работы. Функция ничего не
1606возвращает. Далее следует описание вспомогательной рекурсивной
1607функции.
1608#+begin_src c
1609void
1610find_hamiltonian_cycles (GRAPH g)
1611{
1612 const char *filename = "hamiltonian-cycles.txt";
1613
1614 if (g->vertex_count > 20) {
1615 printf ("Graph is too large (>20v), iterative algorithm will take too long\n");
1616 return;
1617 }
1618
1619 FILE *fd = fopen (filename, "w+");
1620
1621
1622 struct path path = {0};
1623 struct path min_path = {0};
1624 size_t cycle_count = 0;
1625 double min_path_weight = INFINITY;
1626 for (size_t i = 0; i < g->vertex_count; ++i) {
1627 DYNAMIC_ARRAY_RESET (path);
1628 DYNAMIC_ARRAY_APPEND (path, i);
1629 find_hamiltonian_recursive (g, fd, &cycle_count, i, &path, 0, &min_path, &min_path_weight);
1630 }
1631
1632 fclose (fd);
1633
1634 printf ("CYCLES_TOTAL: %zu\n", cycle_count);
1635 printf ("All cycles are saved here: %s\n", filename);
1636 printf ("Cycle with minimum weight (%.0lf): ", min_path_weight);
1637 DYNAMIC_ARRAY_FOREACH (vertex, min_path) {
1638 if (vertex != min_path.items)
1639 printf (" -> ");
1640 printf ("%zu", *vertex);
1641 } printf ("\n");
1642 DYNAMIC_ARRAY_APPEND (min_path, g->vertex_count);
1643 free (g->highlighted_path);
1644 g->highlighted_path = min_path.items;
1645
1646
1647 DYNAMIC_ARRAY_FREE (path);
1648}
1649#+end_src
1650
1651Вспомогательная рекурсивная функция получает указатель на структуру
1652графа, поток для записи циклов, счётчик количества найденных циклов
1653для ограничения поиска, начальную точку поиска, указатель на структуру
1654рабочего пути и её весь, указатель на структуру минимального пути и её
1655весь. Функция ничего не возвращает, минимальный цикл и его весь
1656сохранены через указатели, а всё циклы записаны в файл.
1657#+begin_src c
1658void
1659find_hamiltonian_recursive (GRAPH g, FILE *fd, size_t *cycle_count,
1660 size_t start, PATH path,
1661 double path_weight, PATH min_path,
1662 double *min_path_weight)
1663{
1664 if (*cycle_count >= 1000000)
1665 return;
1666
1667 // Path is built
1668 if (path->count == g->vertex_count) {
1669 size_t last = path->items[path->count - 1];
1670 if (gsl_matrix_get (g->adjecency_matrix, last, start) ||
1671 gsl_matrix_get (g->adjecency_matrix, start, last)) {
1672 *cycle_count += 1;
1673
1674 path_weight +=
1675 gsl_matrix_get (g->weight_matrix, start, last) +
1676 gsl_matrix_get (g->weight_matrix, last, start);
1677 DYNAMIC_ARRAY_APPEND (*path, start);
1678 if (*min_path_weight > path_weight) {
1679 DYNAMIC_ARRAY_COPY_OTHER (*min_path, *path);
1680 *min_path_weight = path_weight;
1681 }
1682
1683 for (size_t i = 0; i < path->count; ++i)
1684 fprintf (fd, "%zu ", path->items[i]);
1685 fprintf (fd, "@ %.0lf\n", path_weight);
1686 path->count -= 1;
1687 }
1688 return;
1689 }
1690
1691 // Continue building
1692 for (size_t i = 0; i < g->vertex_count; ++i) {
1693 size_t last = path->items[path->count - 1];
1694 if (!gsl_matrix_get (g->adjecency_matrix, last, i) &&
1695 !gsl_matrix_get (g->adjecency_matrix, i, last))
1696 continue;
1697
1698 bool used = false;
1699 DYNAMIC_ARRAY_FOREACH (v, *path) {
1700 if (*v == i) {
1701 used = true;
1702 break;
1703 }
1704 } if (used) continue;
1705
1706 double new_weight = path_weight
1707 + gsl_matrix_get (g->weight_matrix, last, i)
1708 + gsl_matrix_get (g->weight_matrix, i, last);
1709 DYNAMIC_ARRAY_APPEND (*path, i);
1710 find_hamiltonian_recursive (g, fd, cycle_count, start, path, new_weight, min_path, min_path_weight);
1711 path->count -= 1;
1712 }
1713}
1714#+end_src
1715
1716* Результаты работы
1717*Создание графа с 8 вершинами:*
1718#+attr_latex: :height 10cm :float nil
1719[[./graph1.png]]
1720
1721#+begin_src text
1722ADJECENCY_MATRIX:
1723 [00][01][02][03][04][05][06][07]
1724[0] 0 0 0 0 0 1 0 0
1725[1] 0 0 1 1 0 0 1 1
1726[2] 0 0 0 0 1 0 0 0
1727[3] 0 0 0 0 0 1 0 0
1728[4] 0 0 0 0 0 1 0 1
1729[5] 0 0 0 0 0 0 1 1
1730[6] 0 0 0 0 0 0 0 1
1731[7] 0 0 0 0 0 0 0 0
1732
1733WEIGHT/COST_MATRIX:
1734 [00][01][02][03][04][05][06][07]
1735[0] 0 0 0 0 0 7 0 0
1736[1] 0 0 4 2 0 0 8 2
1737[2] 0 0 0 0 5 0 0 0
1738[3] 0 0 0 0 0 4 0 0
1739[4] 0 0 0 0 0 7 0 2
1740[5] 0 0 0 0 0 0 2 5
1741[6] 0 0 0 0 0 0 0 1
1742[7] 0 0 0 0 0 0 0 0
1743
1744CAPACITY_MATRIX:
1745 [00][01][02][03][04][05][06][07]
1746[0] 0 0 0 0 0 3 0 0
1747[1] 0 0 4 1 0 0 1 6
1748[2] 0 0 0 0 7 0 0 0
1749[3] 0 0 0 0 0 6 0 0
1750[4] 0 0 0 0 0 9 0 8
1751[5] 0 0 0 0 0 0 6 5
1752[6] 0 0 0 0 0 0 0 1
1753[7] 0 0 0 0 0 0 0 0
1754#+end_src
1755
1756*Метод Шимбелла*
1757#+begin_src text
1758SHIMBELL METHOD EDGE COUNT: 2
1759MIN PATH MATRIX:
1760 [000][001][002][003][004][005][006][007]
1761[0] inf inf inf inf inf inf inf 10
1762[1] inf inf inf inf inf 16 8 11
1763[2] inf inf inf inf inf inf 14 17
1764[3] inf inf inf inf inf inf inf 7
1765[4] inf inf inf inf inf inf inf 10
1766[5] inf inf inf inf inf inf inf inf
1767[6] inf inf inf inf inf inf inf inf
1768[7] inf inf inf inf inf inf inf inf
1769 #+end_src
1770
1771*Определение количества маршрутов из вершины в вершину*
1772 #+begin_src text
1773FROM: 0
1774TO: 7
1775ROUTE COUNT FROM 0 TO 7: 2
1776
1777FROM: 2
1778TO: 7
1779ROUTE COUNT FROM 2 TO 7: 3
1780
1781FROM: 5
1782TO: 0
1783NO ROUTES FROM 5 TO 0
1784 #+end_src
1785
1786*Алгоритм Дейкстры*
1787#+attr_latex: :height 10cm :float nil
1788[[./graph2.png]]
1789
1790 #+begin_src text
1791MIN
1792FROM: 2
1793TO: 7
1794DISTANCEVECTOR: (inf inf inf 0 inf 5 12 14 7)
1795PATH: 2 -> 4 -> 7
1796
1797FROM: 0
1798TO: 7
1799DISTANCE VECTOR: (0 0 inf inf inf inf 7 9 10)
1800PATH: 0 -> 5 -> 6 -> 7
1801
1802FROM: 2
1803TO: 0
1804DISTANCE VECTOR: (inf inf inf 0 inf 5 12 14 7)
1805NO PATH FROM 2 TO 0
1806#+end_src
1807
1808*Алгоритм Флойда-Уоршелла*
1809#+attr_latex: :height 10cm :float nil
1810[[./graph3-1.png]]
1811#+attr_latex: :height 10cm :float nil
1812[[./graph3-2.png]]
1813#+begin_src text
1814MAX
1815FROM: 2
1816TO: 7
1817DISTANCE MATRIX:
1818 [0] [1] [2] [3] [4] [5] [6] [7]
1819[0] 0-inf-inf-inf-inf 7 9 12
1820[1]-inf 0 4 2 9 16 18 21
1821[2]-inf-inf 0-inf 5 12 14 17
1822[3]-inf-inf-inf 0-inf 4 6 9
1823[4]-inf-inf-inf-inf 0 7 9 12
1824[5]-inf-inf-inf-inf-inf 0 2 5
1825[6]-inf-inf-inf-inf-inf-inf 0 1
1826[7]-inf-inf-inf-inf-inf-inf-inf 0
1827PATH: 2 -> 4 -> 5 -> 7
1828 #+end_src
1829
1830*Алгоритм Форда-Фулкерсона*
1831#+attr_latex: :height 10cm :float nil
1832[[./graph4.png]]
1833
1834 #+begin_src text
1835FROM: 2
1836TO: 7
1837MAX_FLOW: 7
1838
1839FROM: 4
1840TO: 7
1841MAX_FLOW: 14
1842#+end_src
1843
1844*Вычисление потока минимальной стоимости*
1845#+attr_latex: :height 10cm :float nil
1846[[./graph5.png]]
1847
1848 #+begin_src text
1849FROM: 4
1850TO: 7
1851REQUIRED_FLOW: [14*2/3] = 9
1852FLOW_MATRIX:
1853 [000][001][002][003][004][005][006][007]
1854[0] 0 0 0 0 0 0 0 0
1855[1] 0 0 0 0 0 0 0 0
1856[2] 0 0 0 0 0 0 0 0
1857[3] 0 0 0 0 0 0 0 0
1858[4] 0 0 0 0 0 1 0 8
1859[5] 0 0 0 0 0 0 1 0
1860[6] 0 0 0 0 0 0 0 1
1861[7] 0 0 0 0 0 0 0 0
1862MIN_COST: 26
1863#+end_src
1864
1865*Определение количества возможных остов*
1866 #+begin_src text
1867KIRCHHOFF_MATRIX:
1868 [000][001][002][003][004][005][006][007]
1869[0] 1 0 0 0 0 -1 0 0
1870[1] 0 4 -1 -1 0 0 -1 -1
1871[2] 0 -1 2 0 -1 0 0 0
1872[3] 0 -1 0 2 0 -1 0 0
1873[4] 0 0 -1 0 3 -1 0 -1
1874[5] -1 0 0 -1 -1 5 -1 -1
1875[6] 0 -1 0 0 0 -1 3 -1
1876[7] 0 -1 0 0 -1 -1 -1 4
1877SPANNING TREE COUNT 181
1878#+end_src
1879
1880*Прим, Борувка и коды Прьюфера*
1881#+attr_latex: :height 10cm :float nil
1882[[./graph6.png]]
1883
1884#+begin_src text
1885PRIM
1886MINIMUM_SPANNING_TREE_WEIGHTS:
1887 [000][001][002][003][004][005][006][007]
1888[0] 0 0 0 0 0 7 0 0
1889[1] 0 0 4 2 0 0 0 2
1890[2] 0 4 0 0 0 0 0 0
1891[3] 0 2 0 0 0 0 0 0
1892[4] 0 0 0 0 0 0 0 2
1893[5] 7 0 0 0 0 0 2 0
1894[6] 0 0 0 0 0 2 0 1
1895[7] 0 2 0 0 2 0 1 0
1896TOTAL_WEIGHT: 20
1897ITERATION_COUNT: 448
1898MINIMAL_SPANNING_TREE:
1899 [000][001][002][003][004][005][006][007]
1900[0] 0 0 0 0 0 7 0 0
1901[1] 0 0 4 2 0 0 0 2
1902[2] 0 4 0 0 0 0 0 0
1903[3] 0 2 0 0 0 0 0 0
1904[4] 0 0 0 0 0 0 0 2
1905[5] 7 0 0 0 0 0 2 0
1906[6] 0 0 0 0 0 2 0 1
1907[7] 0 2 0 0 2 0 1 0
1908PRUFER_CODE: 5 1 1 7 7 6 7
1909SAVED_WEIGHTS: 7 4 2 2 2 2 1
1910DECODED_MINIMAL_SPANNING_TREE:
1911 [000][001][002][003][004][005][006][007]
1912[0] 0 0 0 0 0 7 0 0
1913[1] 0 0 4 2 0 0 0 2
1914[2] 0 4 0 0 0 0 0 0
1915[3] 0 2 0 0 0 0 0 0
1916[4] 0 0 0 0 0 0 0 2
1917[5] 7 0 0 0 0 0 2 0
1918[6] 0 0 0 0 0 2 0 1
1919[7] 0 2 0 0 2 0 1 0
1920Success, matrices the same!
1921#+end_src
1922
1923#+begin_src text
1924BORUVKA
1925MINIMUM_SPANNING_TREE_WEIGHTS:
1926 [000][001][002][003][004][005][006][007]
1927[0] 0 0 0 0 0 7 0 0
1928[1] 0 0 4 2 0 0 0 2
1929[2] 0 4 0 0 0 0 0 0
1930[3] 0 2 0 0 0 0 0 0
1931[4] 0 0 0 0 0 0 0 2
1932[5] 7 0 0 0 0 0 2 0
1933[6] 0 0 0 0 0 2 0 1
1934[7] 0 2 0 0 2 0 1 0
1935TOTAL_WEIGHT: 20
1936ITERATION_COUNT: 44
1937MINIMAL_SPANNING_TREE:
1938 [000][001][002][003][004][005][006][007]
1939[0] 0 0 0 0 0 7 0 0
1940[1] 0 0 4 2 0 0 0 2
1941[2] 0 4 0 0 0 0 0 0
1942[3] 0 2 0 0 0 0 0 0
1943[4] 0 0 0 0 0 0 0 2
1944[5] 7 0 0 0 0 0 2 0
1945[6] 0 0 0 0 0 2 0 1
1946[7] 0 2 0 0 2 0 1 0
1947PRUFER_CODE: 5 1 1 7 7 6 7
1948SAVED_WEIGHTS: 7 4 2 2 2 2 1
1949DECODED_MINIMAL_SPANNING_TREE:
1950 [000][001][002][003][004][005][006][007]
1951[0] 0 0 0 0 0 7 0 0
1952[1] 0 0 4 2 0 0 0 2
1953[2] 0 4 0 0 0 0 0 0
1954[3] 0 2 0 0 0 0 0 0
1955[4] 0 0 0 0 0 0 0 2
1956[5] 7 0 0 0 0 0 2 0
1957[6] 0 0 0 0 0 2 0 1
1958[7] 0 2 0 0 2 0 1 0
1959Success, matrices the same!
1960#+end_src
1961
1962*Эйлер*
1963#+attr_latex: :height 10cm :float nil
1964[[./graph7.png]]
1965
1966#+begin_src text
1967Added edge: 0 -> 4 (9/6)
1968Removed edge: 5 -> 6
1969ADJECENCY_MATRIX:
1970 [000][001][002][003][004][005][006][007]
1971[0] 0 0 0 0 1 1 0 0
1972[1] 0 0 1 1 0 0 1 1
1973[2] 0 0 0 0 1 0 0 0
1974[3] 0 0 0 0 0 1 0 0
1975[4] 0 0 0 0 0 1 0 1
1976[5] 0 0 0 0 0 0 0 1
1977[6] 0 0 0 0 0 0 0 1
1978[7] 0 0 0 0 0 0 0 0
1979EULER_CYCLE: 0 -> 5 -> 7 -> 6 -> 1 -> 7 -> 4 -> 5 -> 3 -> 1 -> 2 -> 4 -> 0
1980#+end_src
1981
1982*Гаммильтон*
1983#+attr_latex: :height 10cm :float nil
1984[[./graph8.png]]
1985
1986#+begin_src text
1987Added edge: 0 -> 2 (3/1)
1988CYCLES_TOTAL: 16
1989All cycles are saved here: hamiltonian-cycles.txt
1990Cycle with minimum weight (30): 0 -> 2 -> 4 -> 7 -> 6 -> 1 -> 3 -> 5 -> 0
1991#+end_src
1992
1993* Заключение
1994:PROPERTIES:
1995:UNNUMBERED: t
1996:END:
1997Результатом работы стала программа, написанная на языке
1998программирования Си (=-std=gnu99=) с использованием библиотеки для
1999рисования Raylib, выполняющая все поставленые задачи:
20001. Поиск экстремальных путей методом Шимбелла;
20012. Определение возможности построение маршрута;
20023. Поиск кратчайших путей (алгоритмы Дейкстры и Флойда-Уоршелла);
20034. Поиск максимального потока (алгоритм Форда-Фалкерсона) и потока
2004 минимальной стоимости;
20055. Поиск числа остовых деревьев (матричная теорема Кирхгофа);
20066. Построение минимального по весу остова (алгоритмы Прима и Борувки);
20077. Кодирование остова с помощью кода Прьюфера;
20088. Построение эйлерова цикла;
20099. Построение гамильтонова цикла;
201010. Решение задачи коммивояжёра.
2011
2012*Сравнения алгоритмов по количеству итерации и сложности:*
2013- У классического алгоритма Дейкстры меньше итерации и сложность
2014 ($\mathcal{O}(n^2)$), чем у алгоритма Флойда-Уоршалла
2015 ($\mathcal{O}(n^3)$).
2016- У алгоритма Борувки меньше итерации и сложность ($\mathcal{O}(q \log
2017 p)$), чем у алгоритма Прима ($\mathcal{O}(p^2)$).
2018
2019*Достоинства программы:*
2020- Программа качественно, за счёт пружинного встраивателя Идса, рисует
2021 графы, выделяя результаты алгоритмов.
2022- Для перемножения матриц используется BLAS подпрограмма =dgemm=.
2023
2024*Недостатки программы:*
2025- Неудобство переключения между окном программы, для выбора действия
2026 из меню, и консолью, для ввода и получения текстовой информации.
2027- Нет возможности легко сохранить и загрузить граф, или хотя бы
2028 листать графы созданные в одном сеансе.
2029
2030*Масштабирование программы:* Относительно легко можно добавить новые
2031алгоритмы и отображения графов, но у графа не может быть динамически
2032определённое количество матриц, хранящих разные данные, все
2033фиксировано при сборке программы.
2034
2035* Используемая литература
2036:PROPERTIES:
2037:UNNUMBERED: t
2038:END:
20391. Ф.А.Новиков. Дискретная математика для программистов. СПб: Питер
2040 Пресс, 2009г. 364с.
20412. Р.Н. Вадзинский. Справочник по вероятностным распределениям. СПб:
2042 Наука, 2001г. 294с.
20433. С.Д. Шапорев. Дискретная математика. СПб: БХВ - Петербург,
2044 2006г. 369с.
2045
2046# Local Variables:
2047# org-confirm-babel-evaluate: nil
2048# org-export-async-init-file: "ox-init.el"
2049# org-export-in-background: t
2050# End:
diff --git a/doc/setup.org b/doc/setup.org
new file mode 100644
index 0000000..c70eabd
--- /dev/null
+++ b/doc/setup.org
@@ -0,0 +1,45 @@
1#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline
2#+OPTIONS: author:t broken-links:nil c:nil creator:nil
3#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t
4#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t
5#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t
6#+SELECT_TAGS: export
7#+EXCLUDE_TAGS: noexport
8#+CREATOR: Emacs 29.1 (Org mode 9.6.9)
9#+BIBLIOGRAPHY: biblio.bib
10#+CITE_EXPORT: biblatex
11#+LATEX_COMPILER: xelatex
12#+LATEX_CLASS: spbstu-report
13# #+LATEX_CLASS_OPTIONS: [draft]
14#+LATEX_HEADER: \usepackage{enumitem}
15#+LATEX_HEADER: \usepackage{array}
16#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type
17#+LATEX_HEADER: \usepackage{float}
18#+LATEX_HEADER: \usepackage{tikz}
19#+LATEX_HEADER: \usepackage{pgfplots}
20#+LATEX_HEADER: \pgfplotsset{compat=1.18}
21#+LATEX_HEADER: \usepackage{afterpage}
22#+LATEX_HEADER: \usepackage{minted}
23#+LATEX_HEADER: \usemintedstyle{bw}
24#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines}
25#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
26#+LATEX_HEADER: \usepackage[plain]{algorithm}
27#+LATEX_HEADER: \usepackage{algpseudocode}
28#+LATEX_HEADER: \makeatletter
29#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм}
30#+LATEX_HEADER: \makeatother
31#+LATEX_HEADER: \providecommand{\reportof}[1]{}
32#+LATEX_HEADER: \providecommand{\subject}[1]{}
33#+LATEX_HEADER: \providecommand{\reviewer}[1]{}
34#+LATEX_HEADER: \providecommand{\reviewertitle}[1]{}
35#+LATEX_HEADER: \providecommand{\hypersetup}[1]{}
36#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
37#+LATEX_HEADER: \setmainfont{Times New Roman}
38#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff]
39#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}}
40#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label}
41#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}}
42#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt}
43#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt}
44#+LATEX_HEADER: \hypersetup{hidelinks}
45#+LATEX_HEADER: \newcommand{\overbar}[1]{\mkern 1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu}
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls
new file mode 100644
index 0000000..422edf2
--- /dev/null
+++ b/doc/spbstu-report.cls
@@ -0,0 +1,73 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов]
3
4%
5% Support font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12\LoadClass[a4paper]{gost-7-32}
13
14\RequirePackage{csquotes}
15\RequirePackage{amsmath}
16\RequirePackage{adjustbox}
17\RequirePackage{setspace}
18
19\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}}
20
21\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
22\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
23\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
24\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
25\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
26\renewcommand{\maketitle}{
27 \begin{titlepage}
28 \begin{center}
29 \vspace{2cm}
30 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
31
32 \normalsize{Федеральное государственное автономное
33 образовательное учреждение высшего образования
34 \enquote{Санкт-Петербургский политехнический университет Петра Великого}}
35
36 \vspace{0.5cm}
37 \normalsize{Институт компьютерных наук и кибербезопасности}
38
39 \normalsize{Высшая школа технологии искусственного интеллекта}
40
41 \normalsize{Направление 02.03.01 Математика и компьютерные науки}
42
43 \vspace{2cm}
44 \LARGE{ОТЧЁТ}
45
46 \normalsize{\@reportof}
47
48 \large{\@subject}
49
50 \large{\textit{\@title}}
51 \end{center}
52
53 \vspace{3cm}
54 \small{
55 \begin{tabular}{lrrl}
56 \!\!\!Студент, & \hspace{2cm} & & \\
57 \!\!\!группы 5130201/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\
58 \!\!\!Преподаватель, & \hspace{2cm} & \\
59 \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\
60 &&\hspace{5cm}
61 \end{tabular}
62 \begin{flushright}
63 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
64 \end{flushright}
65 }
66
67 \vspace*{\fill}
68 \begin{center}
69 \small{Санкт-Петербург, \@date}
70 \end{center}
71 \end{titlepage}
72 \setcounter{page}{2}
73}
diff --git a/manifest.scm b/manifest.scm
new file mode 100644
index 0000000..c640265
--- /dev/null
+++ b/manifest.scm
@@ -0,0 +1,58 @@
1(use-modules (gnu packages base)
2 (gnu packages commencement)
3 (gnu packages tex)
4 ;; (nongnu packages fonts)
5 (gnu packages game-development)
6 (gnu packages maths))
7
8(packages->manifest (list
9 raylib
10 gsl
11 openblas
12 gcc-toolchain
13
14 ;; font-microsoft-times-new-roman
15 ;; texlive-scheme-small
16 ;; texlive-lh
17 ;; texlive-cm
18 ;; texlive-type1cm
19 ;; texlive-ec
20 ;; texlive-wrapfig
21 ;; texlive-adjustbox
22 ;; texlive-graphics
23 ;; texlive-hyperref
24 ;; texlive-latex-fonts
25 ;; texlive-amsfonts
26 ;; texlive-cyrillic
27 ;; texlive-babel-russian
28 ;; texlive-geometry
29 ;; texlive-enumitem
30 ;; texlive-csquotes
31 ;; texlive-float
32 ;; texlive-biblatex
33 ;; texlive-biber
34 ;; texlive-pgfplots
35 ;; texlive-trimspaces
36 ;; texlive-catchfile
37 ;; texlive-hyphen-complete
38 ;; texlive-capt-of
39 ;; texlive-minted
40 ;; texlive-titlesec
41 ;; texlive-titling
42 ;; texlive-scheme-basic
43 ;; texlive-fontspec
44 ;; texlive-beamer
45 ;; texlive-microtype
46 ;; texlive-siunitx
47 ;; texlive-textpos
48 ;; texlive-mathspec
49 ;; texlive-etoolbox
50 ;; texlive-extsizes
51 ;; texlive-cm-super
52 ;; texlive-amsmath
53 ;; texlive-transparent
54 ;; texlive-ucs
55 ;; texlive-ulem
56 ;; texlive-algorithms
57 ;; texlive-algorithmicx
58 ))
diff --git a/src/config.h b/src/config.h
new file mode 100644
index 0000000..fa04908
--- /dev/null
+++ b/src/config.h
@@ -0,0 +1,66 @@
1#ifndef INCLUDED_CONFIG_H
2#define INCLUDED_CONFIG_H
3
4#define INITIAL_SCREEN_WIDTH 500
5#define INITIAL_SCREEN_HEIGHT 500
6#define WINDOW_TITLE "Graph visualization"
7
8// // TODO(cmmm): compute
9#define BUTTON_HEIGHT 30
10#define BUTTON_WIDTH 300
11#define PADDING 10
12
13#define VERTEX_RADIUS 20
14#define BASE_LINE_THICKNESS 6
15
16#define FONT_SIZE 20
17#define TEXT_SPACING 1
18
19#define INITIAL_VERTEX_COUNT 8
20
21#define MAX_VERTEX_COUNT ((size_t) 40)
22#define MAX_WEIGHT ((double) 10)
23#define MAX_CAPACITY ((double) MAX_WEIGHT)
24
25#define DIST_N 10
26#define DIST_B 20
27#define DIST_R 1
28#define DIST_C 10
29
30#define MODEL_L ((double) 1.0)
31#define MODEL_C_REP ((double) 1.0)
32#define MODEL_C_SPRING ((double) 10.0)
33#define MODEL_COOLING_FACTOR ((double) 0.9)
34
35#define DARK_THEME
36#if defined (LIGHT_THEME)
37#define BACKGROUND_COLOR WHITE
38#define VERTEX_COLOR RED
39#define VERTEX_OUTLINE_COLOR MAROON
40#define VERTEX_OUTLINE_HIGHLIGHTED_COLOR BLACK
41#define VERTEX_TEXT_COLOR WHITE
42#define EDGE_TEXT_COLOR BLACK
43#define BUTTON_COLOR LIGHTGRAY
44#define BUTTON_OUTLINE_COLOR GRAY
45#define BUTTON_HOVER_COLOR MAROON
46#define BUTTON_HOVER_OUTLINE_COLOR RED
47#define BUTTON_TEXT_COLOR BLACK
48#define BUTTON_TEXT_HOVER_COLOR WHITE
49#elif defined (DARK_THEME)
50#define BACKGROUND_COLOR BLACK
51// #define EDGE_MIN_COLOR WHITE
52// #define EDGE_MAX_COLOR WHITE
53#define EDGE_TEXT_COLOR WHITE
54#define VERTEX_COLOR RED
55#define VERTEX_OUTLINE_COLOR MAROON
56#define VERTEX_OUTLINE_HIGHLIGHTED_COLOR WHITE
57#define VERTEX_TEXT_COLOR WHITE
58#define BUTTON_COLOR DARKGRAY
59#define BUTTON_OUTLINE_COLOR GRAY
60#define BUTTON_HOVER_COLOR MAROON
61#define BUTTON_HOVER_OUTLINE_COLOR RED
62#define BUTTON_TEXT_COLOR LIGHTGRAY
63#define BUTTON_TEXT_HOVER_COLOR LIGHTGRAY
64#endif
65
66#endif
diff --git a/src/distribution-test.c b/src/distribution-test.c
new file mode 100644
index 0000000..178bf73
--- /dev/null
+++ b/src/distribution-test.c
@@ -0,0 +1,63 @@
1#define _GNU_SOURCE
2#include <stdlib.h>
3#include <string.h>
4#include <stdio.h>
5#include <time.h>
6#include <raylib.h>
7
8#include "distribution.h"
9
10int
11main (void)
12{
13 const int screen_padding = 10;
14 const int notation_height = 20;
15
16 int screen_width = 800;
17 int screen_height = 450;
18
19 SetConfigFlags (FLAG_MSAA_4X_HINT |
20 FLAG_WINDOW_RESIZABLE |
21 FLAG_VSYNC_HINT |
22 FLAG_WINDOW_UNDECORATED);
23 InitWindow (screen_width, screen_height, "graph");
24 SetTargetFPS (60);
25
26 srand (time (NULL));
27 struct distribution dist;
28 // distribution_init (&dist, 20, 20, 1, 10);
29 distribution_init (&dist, 11, 20, 1, 10);
30
31 int arr[dist.n - 1];
32 memset (arr, 0, sizeof (arr));
33 int iterrations = 10000;
34 for (int i = 0; i < iterrations; ++i)
35 arr[distribution_rand (&dist)] += 1;
36
37 while (!WindowShouldClose ()) {
38 BeginDrawing ();
39 ClearBackground (WHITE);
40
41 screen_width = GetScreenWidth ();
42 screen_height = GetScreenHeight ();
43
44 const int rect_width = (screen_width - screen_padding)/(dist.n - 1) - screen_padding;
45 const int rect_max_height = screen_height - 2*screen_padding - notation_height;
46 for (int i = 0; i < dist.n - 1; ++i) {
47 const int rect_height = rect_max_height*arr[i]/iterrations;
48 DrawRectangle ((i + 1)*screen_padding + i*rect_width,
49 screen_padding + rect_max_height - rect_height,
50 rect_width, rect_height, BLACK);
51
52 char *perc;
53 asprintf (&perc, "%2d%%", arr[i]*100/iterrations);
54 DrawText (perc, (i + 1)*screen_padding + i*rect_width + rect_width/4, screen_height - screen_padding - 3*notation_height/4, notation_height, BLACK);
55 }
56
57 EndDrawing ();
58 }
59
60 CloseWindow ();
61
62 return EXIT_SUCCESS;
63}
diff --git a/src/distribution.c b/src/distribution.c
new file mode 100644
index 0000000..7887ba3
--- /dev/null
+++ b/src/distribution.c
@@ -0,0 +1,57 @@
1#define _GNU_SOURCE
2#include <stdlib.h>
3#include <assert.h>
4#include <stdio.h>
5
6#include "distribution.h"
7
8void
9distribution_init (DISTRIBUTION dist,
10 unsigned int n,
11 unsigned int b,
12 unsigned int r,
13 int c)
14{
15 assert (n > 0);
16 assert (b > 0);
17 assert (r > 0);
18 assert (b + r + c*(n - 1) > 0);
19
20 dist->n = n;
21 dist->b = b;
22 dist->r = r;
23 dist->c = c;
24 dist->p0 = r/(float)(b + r);
25 for (int i = 1; i < n; ++i) {
26 dist->p0 *= (r + i*c)/(float)(b + r + i*c);
27 }
28}
29
30int
31distribution_rand (DISTRIBUTION dist)
32{
33 for (;;) {
34 double p = dist->p0;
35 double r = rand ()/(double) RAND_MAX;
36 // printf ("r = %f, p = %f\n", r, p);
37 unsigned int x = 0;
38
39 while (x < dist->n - 1) {
40 r -= p;
41 if (r < 0)
42 return x;
43 x += 1;
44 p *= ((dist->n - 1 - x) *
45 (dist->b + (x - 1)*dist->c) /(double)
46 (x*(dist->r + (dist->n - x)*dist->c)));
47 // printf ("p = %f\n", p);
48 } // putchar ('\n');
49 }
50 // return dist->n;
51}
52
53double
54distribution_nrand (DISTRIBUTION dist)
55{
56 return distribution_rand (dist)/(double) (dist->n - 2);
57}
diff --git a/src/distribution.h b/src/distribution.h
new file mode 100644
index 0000000..c4b20b9
--- /dev/null
+++ b/src/distribution.h
@@ -0,0 +1,22 @@
1#ifndef INCLUDED_DISTRIBUTION_H
2#define INCLUDED_DISTRIBUTION_H
3
4// Multivariate Pólya distribution
5typedef struct distribution
6{
7 unsigned int n;
8 unsigned int b;
9 unsigned int r;
10 int c;
11 double p0;
12}* DISTRIBUTION;
13
14void distribution_init (DISTRIBUTION dist,
15 unsigned int n,
16 unsigned int b,
17 unsigned int r,
18 int c);
19int distribution_rand (DISTRIBUTION dist);
20double distribution_nrand (DISTRIBUTION dist);
21
22#endif
diff --git a/src/dynamic-array.h b/src/dynamic-array.h
new file mode 100644
index 0000000..bd470d5
--- /dev/null
+++ b/src/dynamic-array.h
@@ -0,0 +1,74 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_APPEND_OTHER(DYNAMIC_ARRAY, OTHER) \
49 DYNAMIC_ARRAY_APPEND_MANY ((DYNAMIC_ARRAY), (OTHER).items, (OTHER).count)
50
51#define DYNAMIC_ARRAY_COPY_OTHER(DYNAMIC_ARRAY, OTHER) \
52 ({ \
53 DYNAMIC_ARRAY_RESET ((DYNAMIC_ARRAY)); \
54 DYNAMIC_ARRAY_APPEND_OTHER ((DYNAMIC_ARRAY), (OTHER)); \
55 })
56
57#define DYNAMIC_ARRAY_ERASE(DYNAMIC_ARRAY, IDX) \
58 ({ \
59 memmove (&(DYNAMIC_ARRAY).items[(IDX) + 0], \
60 &(DYNAMIC_ARRAY).items[(IDX) + 1], \
61 ((DYNAMIC_ARRAY).count - (IDX) - 1) \
62 * sizeof (*(DYNAMIC_ARRAY).items)); \
63 (DYNAMIC_ARRAY).count -= 1; \
64 })
65
66#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
67
68#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
69
70#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
71 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
72 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
73
74#endif
diff --git a/src/graph.c b/src/graph.c
new file mode 100644
index 0000000..dd7058b
--- /dev/null
+++ b/src/graph.c
@@ -0,0 +1,1311 @@
1#include "graph.h"
2#include "config.h"
3#include "utils.h"
4#include "dynamic-array.h"
5#include <string.h>
6#include <gsl/gsl_blas.h>
7#include <gsl/gsl_eigen.h>
8#include <gsl/gsl_sort_vector.h>
9
10#define ALLOC_SQUARE_GSL_MATRIX(n) gsl_matrix_calloc ((n), (n))
11
12gsl_matrix *
13shimbell_method (GRAPH g, size_t edge_count, bool max)
14{
15 size_t n = g->vertex_count;
16 gsl_matrix *adj = g->weight_matrix;
17 gsl_matrix *shimbell = ALLOC_SQUARE_GSL_MATRIX (n);
18
19 gsl_matrix_memcpy (shimbell, adj);
20 if (n == 1)
21 return shimbell;
22
23 gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX (n);
24 for (size_t l = 0; l < edge_count; ++l) {
25 gsl_matrix_memcpy (tmp, shimbell);
26 for (size_t i = 0; i < n; ++i) {
27 for (size_t j = 0; j < n; ++j) {
28 double bestval = max ? 0 : INFINITY;
29 for (size_t k = 0; k < n; ++k) {
30 double a = gsl_matrix_get (tmp, k, j);
31 double b = gsl_matrix_get (adj, i, k);
32 if (a == 0 || b == 0)
33 continue;
34 double val = a + b;
35 if (max ? val > bestval
36 : val < bestval) {
37 bestval = val;
38 }
39 } gsl_matrix_set (shimbell, i, j, bestval);
40 }
41 }
42 } gsl_matrix_free (tmp);
43
44 return shimbell;
45}
46
47size_t
48graph_count_routes (GRAPH g, size_t from, size_t to)
49{
50 size_t n = g->vertex_count;
51 gsl_matrix *adj = g->adjecency_matrix;
52 gsl_matrix *con = ALLOC_SQUARE_GSL_MATRIX(n);
53 gsl_matrix *pow = ALLOC_SQUARE_GSL_MATRIX(n);
54 gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX(n);
55
56 for (size_t e = 0; e < n*n; ++e)
57 con->data[e] = adj->data[e] != 0 ? 1 : 0;
58 gsl_matrix_memcpy (pow, con);
59 gsl_matrix_memcpy (tmp, con);
60
61 size_t count = gsl_matrix_get (pow, from, to);
62 for (size_t k = 0; k < n - 2; ++k) {
63 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
64 1.0, tmp, con,
65 0.0, pow);
66 count += gsl_matrix_get (pow, from, to);
67 gsl_matrix *swap = tmp;
68 tmp = pow;
69 pow = swap;
70 }
71
72 gsl_matrix_free (con);
73 gsl_matrix_free (tmp);
74 gsl_matrix_free (pow);
75
76 return count;
77}
78
79static inline void
80is_graph_connected_implementation (gsl_matrix *adj, bool *visited, size_t v)
81{
82 size_t n = adj->size1;
83 visited[v] = true;
84 for (size_t i = 0; i < n; ++i) {
85 if (!visited[i] &&
86 (gsl_matrix_get(adj, v, i) ||
87 gsl_matrix_get(adj, i, v))) {
88 is_graph_connected_implementation (adj, visited, i);
89 }
90 }
91}
92
93bool
94is_graph_connected (GRAPH g)
95{
96 size_t n = g->vertex_count;
97 bool visited[n];
98 memset (visited, 0, sizeof (visited));
99 is_graph_connected_implementation (g->adjecency_matrix, visited, 0);
100 for (size_t i = 0; i < n; ++i) {
101 if (!visited[i]) return false;
102 } return true;
103}
104
105bool
106is_graph_algebraically_connected (gsl_matrix *adj)
107{
108 size_t n = adj->size1;
109
110 gsl_matrix *laplacian = gsl_matrix_alloc (n, n);
111 for (size_t i = 0; i < n; ++i) {
112 double deg = 0;
113 for (size_t j = i + 1; j < n; ++j) {
114 double val = gsl_matrix_get (adj, i, j);
115 gsl_matrix_set (laplacian, j, i, val == 0.0 ? 0.0 : -val);
116 deg += gsl_matrix_get (adj, i, j);
117 } gsl_matrix_set (laplacian, i, i, deg);
118 }
119
120 gsl_vector *eval = gsl_vector_alloc (n);
121 gsl_eigen_symm_workspace *w = gsl_eigen_symm_alloc (n);
122 gsl_eigen_symm (laplacian, eval, w);
123 gsl_sort_vector (eval);
124 double fiedler = gsl_vector_get (eval, 1);
125
126 gsl_eigen_symm_free (w);
127 gsl_vector_free (eval);
128 gsl_matrix_free (laplacian);
129
130 return fiedler > 1e-12 ? true : false;
131}
132
133void
134generate_graph (GRAPH g, DISTRIBUTION dist,
135 size_t vertex_count, enum graph_type type)
136{
137 g->vertex_count = vertex_count;
138 g->type = type;
139
140 size_t n = vertex_count;
141 // size_t m = n - 1;
142 size_t m = MIN (n*3/2, (n*n - n)/2);
143
144 g -> adjecency_matrix = ALLOC_SQUARE_GSL_MATRIX(n);
145 g -> weight_matrix = ALLOC_SQUARE_GSL_MATRIX(n);
146 g -> capacity_matrix = ALLOC_SQUARE_GSL_MATRIX(n);
147
148 // for (size_t i = 0; i < n - 1; ++i) {
149 // size_t max_degree = n - i - 1;
150 // size_t degree = floor (distribution_nrand (dist)*(max_degree - 1)) + 1;
151
152 // for (size_t j = 0; j < degree; ++j) {
153 // double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1;
154 // if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2)
155 // weight = -weight;
156 // double capacity = floor (MAX_CAPACITY*distribution_nrand (dist));
157 // gsl_matrix_set (g -> adjecency_matrix, i, j + i + 1, 1);
158 // gsl_matrix_set (g -> weight_matrix, i, j + i + 1, weight);
159 // gsl_matrix_set (g -> capacity_matrix, i, j + i + 1, capacity);
160 // }
161 // }
162
163 for (size_t k = 0; k < m || !is_graph_connected (g); ++k) {
164 size_t r = floor (n*n*distribution_nrand (dist)) + 1;
165 // size_t r = floor (n*n*(rand ()/(double) RAND_MAX)) + 1;
166 ssize_t i = floor ((r - 1)/(double) n);
167 ssize_t j = (r - 1) % n;
168 // printf ("%2zu %zd %zd\n", r, i, j);
169
170 if (i < j && !gsl_matrix_get (g->adjecency_matrix, i, j)) {
171 double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1;
172 if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2)
173 weight = -weight;
174 double capacity = floor (MAX_CAPACITY*distribution_nrand (dist));
175 gsl_matrix_set (g -> adjecency_matrix, i, j, 1);
176 gsl_matrix_set (g -> weight_matrix, i, j, weight);
177 gsl_matrix_set (g -> capacity_matrix, i, j, capacity);
178 } else m += 1;
179 }
180}
181
182size_t *
183dijkstra_positive (GRAPH g, size_t from, size_t to, bool max)
184{
185 struct dijkstra_node
186 {
187 double distance;
188 size_t previous;
189 bool visited;
190 };
191
192 size_t n = g->vertex_count;
193
194 double cost[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT];
195 for (size_t i = 0; i < n; ++i) {
196 for (size_t j = 0; j < n; ++j) {
197 double val = gsl_matrix_get (g->weight_matrix, i, j);
198 if (val == 0)
199 cost[i][j] = max ? -INFINITY : INFINITY;
200 else
201 cost[i][j] = val;
202 }
203 }
204
205 struct dijkstra_node nodes[MAX_VERTEX_COUNT];
206 for (size_t i = 0; i < n; ++i) {
207 nodes[i] = (struct dijkstra_node) {
208 .distance = cost[from][i],
209 .previous = from,
210 .visited = false,
211 };
212 }
213 nodes[from].distance = 0;
214 nodes[from].visited = true;
215
216 for (size_t count = 1; count < n - 1; ++count) {
217 size_t next;
218 double best_distance = max ? -INFINITY : INFINITY;
219 for (size_t i = 0; i < n; i++) {
220 if ((max ? nodes[i].distance > best_distance
221 : nodes[i].distance < best_distance)
222 && !nodes[i].visited) {
223 best_distance = nodes[i].distance;
224 next = i;
225 }
226 }
227
228 nodes[next].visited = true;
229 for (size_t i = 0; i < n; ++i) {
230 if (!nodes[i].visited) {
231 double distance = best_distance + cost[next][i];
232 if ((max ? distance > nodes[i].distance
233 : distance < nodes[i].distance)) {
234 nodes[i].distance = distance;
235 nodes[i].previous = next;
236 }
237 }
238 }
239 }
240
241 printf ("DISTANCE VECTOR: (%.f", nodes[0].distance);
242 for (size_t i = 0; i < n; ++i) {
243 printf (" %.f", nodes[i].distance);
244 } puts (")");
245
246 if (nodes[to].distance == (max ? -INFINITY : INFINITY)) {
247 printf ("NO PATH FROM %zu TO %zu\n", from, to);
248 return NULL;
249 }
250
251 size_t len = 1;
252 for (size_t i = to; i != from; i = nodes[i].previous)
253 len += 1;
254
255 size_t *path = malloc ((len + 1)*sizeof (*path));
256 size_t v = len;
257 path[v--] = n;
258 for (size_t i = to; i != from; i = nodes[i].previous)
259 path[v--] = i;
260 path[v] = from;
261
262 printf ("PATH: %zu", path[0]);
263 for (size_t i = 1; path[i] != n; ++i)
264 printf (" -> %zu", path[i]);
265 putchar ('\n');
266
267 return path;
268}
269
270size_t *
271floyd_warshall (GRAPH g, size_t from, size_t to, bool max)
272{
273 const size_t n = g->vertex_count;
274 double dist[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT];
275 size_t next[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT];
276
277 // initialize dist and next
278 for (size_t u = 0; u < n; ++u) {
279 for (size_t v = 0; v < n; ++v) {
280 if (gsl_matrix_get (g->weight_matrix, u, v) == 0) {
281 dist[u][v] = max ? -INFINITY : INFINITY;
282 next[u][v] = n;
283 } else {
284 dist[u][v] = gsl_matrix_get (g->weight_matrix, u, v);
285 next[u][v] = v;
286 }
287 dist[v][v] = 0;
288 next[v][v] = v;
289 }
290 }
291
292 // compute dist and next
293 for (size_t k = 0; k < n; ++k) {
294 for (size_t i = 0; i < n; ++i) {
295 for (size_t j = 0; j < n; ++j) {
296 if (max ? dist[i][j] < dist[i][k] + dist[k][j]
297 : dist[i][j] > dist[i][k] + dist[k][j]) {
298 dist[i][j] = dist[i][k] + dist[k][j];
299 next[i][j] = next[i][k];
300 }
301 }
302 }
303 }
304
305 puts ("DISTANCE MATRIX:");
306 printf (" ");
307 for (size_t j = 0; j < n; j++)
308 printf (" [%zu]", j);
309 putchar ('\n');
310 for (size_t i = 0; i < n; i++) {
311 printf ("[%zu]", i);
312 for (size_t j = 0; j < n; j++)
313 printf ("%4g", dist[i][j]);
314 putchar ('\n');
315 }
316
317 // find path
318 if (next[from][to] == n) {
319 printf ("NO PATH FROM %zu TO %zu\n", from, to);
320 return NULL;
321 }
322
323 size_t len = 1;
324 for (size_t v = from; v != to; v = next[v][to])
325 len += 1;
326
327 size_t *path = malloc ((len + 1)*sizeof (*path));
328 size_t e = 0;
329 for (size_t v = from; v != to; v = next[v][to])
330 path[e++] = v;
331 path[e++] = to;
332 path[e] = n;
333
334 printf ("PATH: %zu", path[0]);
335 for (size_t i = 1; path[i] != n; ++i)
336 printf (" -> %zu", path[i]);
337 putchar ('\n');
338
339 return path;
340}
341
342void
343graph_unhighlight (GRAPH g)
344{
345 free (g->highlighted_path);
346 g->highlighted_path = NULL;
347 DYNAMIC_ARRAY_RESET (g->highlighted_edges);
348}
349
350void
351graph_edge_set (GRAPH g, size_t from, size_t to,
352 double weight, double capacity)
353{
354 gsl_matrix_set (g -> adjecency_matrix, from, to, weight && capacity);
355 gsl_matrix_set (g -> weight_matrix, from, to, weight);
356 gsl_matrix_set (g -> capacity_matrix, from, to, capacity);
357}
358
359void
360print_graph (GRAPH g)
361{
362 puts ("ADJECENCY_MATRIX:");
363 print_gsl_matrix (g->adjecency_matrix);
364 puts ("WEIGHT/COST_MATRIX:");
365 print_gsl_matrix (g->weight_matrix);
366 puts ("CAPACITY_MATRIX:");
367 print_gsl_matrix (g->capacity_matrix);
368}
369
370bool
371are_vertices_connected (gsl_matrix *g, size_t from, size_t to)
372{
373 size_t n = g->size1;
374 struct stack {
375 size_t *items;
376 size_t count;
377 size_t capacity;
378 };
379
380 struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n);
381 struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n);
382 struct stack *front_stack = &stack1;
383 struct stack *back_stack = &stack2;
384 DYNAMIC_ARRAY_APPEND (*front_stack, from);
385 while (front_stack->count) {
386 DYNAMIC_ARRAY_RESET (*back_stack);
387 DYNAMIC_ARRAY_FOREACH (v, *front_stack) {
388 size_t vertex = *v;
389 for (size_t i = 0; i < n; ++i) {
390 if (gsl_matrix_get (g, vertex, i)) {
391 if (to == i) return true;
392 DYNAMIC_ARRAY_APPEND (*back_stack, i);
393 }
394 }
395 } SWAP (front_stack, back_stack);
396 }
397
398 return false;
399}
400
401void
402highlight_graph (GRAPH g, const gsl_matrix *m)
403{
404 DYNAMIC_ARRAY_RESET (g->highlighted_edges);
405 size_t n = g->vertex_count;
406 for (size_t i = 0; i < n; ++i) {
407 for (size_t j = 0; j < n; ++j) {
408 if (gsl_matrix_get (m, i, j))
409 DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {i, j}));
410 }
411 }
412}
413
414// https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
415// https://algorithms.discrete.ma.tum.de/graph-algorithms/flow-ford-fulkerson/index_en.html
416double
417max_flow_ford_fulkerson (GRAPH g, size_t source, size_t sink)
418{
419 size_t n = g->vertex_count;
420 size_t parents[MAX_VERTEX_COUNT];
421 for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i)
422 parents[i] = n;
423
424 gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n);
425 gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix);
426 double max_flow = 0;
427
428 struct stack {
429 size_t *items;
430 size_t count;
431 size_t capacity;
432 };
433
434 DYNAMIC_ARRAY_RESET (g->highlighted_edges);
435 struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n);
436 struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n);
437 struct stack *front_stack = &stack1;
438 struct stack *back_stack = &stack2;
439 for (;;) {
440 bool visited[MAX_VERTEX_COUNT] = { false };
441 DYNAMIC_ARRAY_RESET (*front_stack);
442 DYNAMIC_ARRAY_APPEND (*front_stack, source);
443 visited[source] = true;
444 while (front_stack->count) {
445 DYNAMIC_ARRAY_RESET (*back_stack);
446 DYNAMIC_ARRAY_FOREACH (v, *front_stack) {
447 size_t vertex = *v;
448 for (size_t i = 0; i < n; ++i) {
449 if (!visited[i] &&
450 gsl_matrix_get (residual_capacity_matrix, vertex, i) > 0) {
451 parents[i] = vertex;
452 if (sink == i) goto found;
453 DYNAMIC_ARRAY_APPEND (*back_stack, i);
454 visited[i] = true;
455 }
456 }
457 } SWAP(front_stack, back_stack);
458 }
459 break;
460
461 found: {
462 double path_flow = INFINITY;
463 for (size_t v = sink; v != source; v = parents[v]) {
464 size_t u = parents[v];
465 DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v}));
466 path_flow = fmin (path_flow, gsl_matrix_get (residual_capacity_matrix,
467 u, v));
468 }
469
470 for (size_t v = sink; v != source; v = parents[v]) {
471 size_t u = parents[v];
472 *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow;
473 *gsl_matrix_ptr (residual_capacity_matrix, v, u) += path_flow;
474 }
475
476 max_flow += path_flow;
477 }
478 }
479
480 gsl_matrix_free (residual_capacity_matrix);
481
482 return max_flow;
483}
484
485// https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG9.pdf
486double
487min_cost_flow (GRAPH g, size_t s, size_t t, double required_flow)
488{
489 size_t n = g->vertex_count;
490 gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n);
491 gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix);
492 gsl_matrix *residual_cost_matrix = gsl_matrix_alloc (n, n);
493 gsl_matrix_memcpy (residual_cost_matrix, g->weight_matrix);
494 gsl_matrix *result_flow_matrix = gsl_matrix_calloc (n, n);
495 double costs[MAX_VERTEX_COUNT];
496 size_t parents[MAX_VERTEX_COUNT];
497 double flow;
498 double min_cost;
499
500 DYNAMIC_ARRAY_RESET (g->highlighted_edges);
501 while (flow < required_flow) {
502 // Bellman-Ford
503 for (size_t i = 0; i < n; ++i) {
504 costs[i] = INFINITY;
505 parents[i] = n;
506 } costs[s] = 0;
507 for (size_t i = 0; i < n - 1; ++i) {
508 for (size_t u = 0; u < n; ++u) {
509 for (size_t v = 0; v < n; ++v) {
510 if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue;
511 double cost = gsl_matrix_get (residual_cost_matrix, u, v);
512 if (costs[u] != INFINITY &&
513 cost != INFINITY &&
514 costs[u] + cost < costs[v]) {
515 costs[v] = costs[u] + cost;
516 parents[v] = u;
517 }
518 }
519 }
520 }
521
522 // If no path
523 if (parents[t] == n) return NAN;
524
525 // Find max flow
526 double path_flow = INFINITY;
527 for (size_t v = t; v != s; v = parents[v]) {
528 size_t u = parents[v];
529 path_flow = fmin (path_flow,
530 gsl_matrix_get (residual_capacity_matrix, u, v));
531 }
532
533 // Apply flow constraint
534 path_flow = fmin (path_flow, required_flow - flow);
535
536 // Update costs and capacities
537 for (int v = t; v != s; v = parents[v]) {
538 int u = parents[v];
539 DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v}));
540 *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow;
541 *gsl_matrix_ptr (result_flow_matrix, u, v) += path_flow;
542 min_cost += path_flow*gsl_matrix_get (residual_cost_matrix, u, v);
543
544 if (gsl_matrix_get (residual_capacity_matrix, u, v) == 0)
545 gsl_matrix_set (residual_cost_matrix, u, v, INFINITY);
546 }
547
548 flow += path_flow;
549 }
550
551 puts ("FLOW_MATRIX:");
552 print_gsl_matrix (result_flow_matrix);
553
554 gsl_matrix_free (residual_capacity_matrix);
555 gsl_matrix_free (residual_cost_matrix);
556 gsl_matrix_free (result_flow_matrix);
557
558 return min_cost;
559}
560
561size_t
562count_spanning_trees (GRAPH g)
563{
564 size_t n = g->vertex_count;
565 gsl_matrix *kirchhoff_matrix = gsl_matrix_calloc (n, n);
566
567 for (size_t i = 0; i < n; i++) {
568 for (size_t j = i; j < n; j++) {
569 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
570 gsl_matrix_get (g->adjecency_matrix, j, i)) {
571 *gsl_matrix_ptr (kirchhoff_matrix, i, i) += 1;
572 *gsl_matrix_ptr (kirchhoff_matrix, j, j) += 1;
573 *gsl_matrix_ptr (kirchhoff_matrix, i, j) = -1;
574 *gsl_matrix_ptr (kirchhoff_matrix, j, i) = -1;
575 }
576 }
577 }
578
579 printf ("KIRCHHOFF_MATRIX:\n");
580 print_gsl_matrix (kirchhoff_matrix);
581
582 size_t count = gsl_matrix_cofactor (kirchhoff_matrix, 0, 0);
583 gsl_matrix_free (kirchhoff_matrix);
584
585 return count;
586}
587
588// https://en.wikipedia.org/wiki/Prim%27s_algorithm
589gsl_matrix *
590min_weight_spannig_tree_prim (GRAPH g)
591{
592 size_t count = 0;
593 double total_weight = 0;
594 size_t n = g->vertex_count;
595 gsl_matrix *remaining_graph = gsl_matrix_alloc (n, n);
596
597 for (size_t i = 0; i < n; ++i) {
598 for (int j = 0; j < n; ++j) {
599 double weight = gsl_matrix_get (g->weight_matrix, i, j);
600 gsl_matrix_set (remaining_graph, i, j, weight == 0 ? INFINITY : weight);
601 }
602 }
603
604 gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n);
605 bool visited[MAX_VERTEX_COUNT] = {0};
606 size_t spanning_tree_vertex_count = 0;
607 while (spanning_tree_vertex_count < g->vertex_count) {
608 double minimum_weight = INFINITY;
609 size_t a;
610 size_t b;
611 for (size_t i = 0 ; i < n; ++i) {
612 for (size_t j = 0; j < n; ++j) {
613 count += 1;
614 double weight = gsl_matrix_get (remaining_graph, i, j);
615 if (weight < minimum_weight &&
616 ((visited[i] != visited[j]) ||
617 spanning_tree_vertex_count == 0)) {
618 minimum_weight = weight;
619 a = i;
620 b = j;
621 }
622 }
623 }
624
625 if (!visited[a] || !visited[b]) {
626 if (!visited[a]) {
627 spanning_tree_vertex_count += 1;
628 visited[a] = true;
629 }
630
631 if (!visited[b]) {
632 spanning_tree_vertex_count += 1;
633 visited[b] = true;
634 }
635
636 total_weight += minimum_weight;
637 }
638
639 gsl_matrix_set (remaining_graph, a, b, INFINITY);
640 gsl_matrix_set (remaining_graph, b, a, INFINITY);
641 gsl_matrix_set (spanning_tree, a, b, minimum_weight);
642 gsl_matrix_set (spanning_tree, b, a, minimum_weight);
643 printf ("%zu %zu = %f\n", a, b, minimum_weight);
644 } gsl_matrix_free (remaining_graph);
645
646 printf ("MINIMUM_SPANNING_TREE_WEIGHTS:\n");
647 print_gsl_matrix (spanning_tree);
648 printf ("TOTAL_WEIGHT: %.0lf\n", total_weight);
649 printf ("ITERATION_COUNT: %zu\n", count);
650
651 return spanning_tree;
652}
653
654// https://en.wikipedia.org/wiki/Bor%C5%AFvka's_algorithm
655gsl_matrix *
656min_weight_spannig_tree_boruvka (GRAPH g)
657{
658 size_t n = g->vertex_count;
659 gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n);
660
661 struct edge_weight {
662 size_t from;
663 size_t to;
664 double weight;
665 };
666
667 size_t number_of_components = g->vertex_count;
668 struct edge_weight lightest_edges[MAX_VERTEX_COUNT];
669 size_t parent_components[MAX_VERTEX_COUNT];
670 size_t next_components[MAX_VERTEX_COUNT];
671
672 for (size_t i = 0; i < n; ++i)
673 parent_components[i] = i;
674
675 size_t count = 0;
676 double min_weight = 0;
677 while (number_of_components > 1) {
678 for (size_t i = 0; i < n; ++i)
679 lightest_edges[i] = (struct edge_weight) { 0, 0, .weight = INFINITY };
680
681 for (size_t u = 0; u < n; ++u) {
682 for (size_t v = 0; v < n; ++v) {
683 if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue;
684 count += 1;
685 double weight =
686 gsl_matrix_get (g->weight_matrix, u, v) +
687 gsl_matrix_get (g->weight_matrix, v, u);
688
689 if (parent_components[u] != parent_components[v]) {
690 if (lightest_edges[parent_components[u]].weight > weight) {
691 lightest_edges[parent_components[u]].weight = weight;
692 lightest_edges[parent_components[u]].from = u;
693 lightest_edges[parent_components[u]].to = v;
694 }
695 if (lightest_edges[parent_components[v]].weight > weight) {
696 lightest_edges[parent_components[v]].weight = weight;
697 lightest_edges[parent_components[v]].from = u;
698 lightest_edges[parent_components[v]].to = v;
699 }
700 }
701 }
702 }
703
704 // Adding selected edges and combining components
705 for (size_t i = 0; i < number_of_components; ++i) {
706 count++;
707
708 double weight = lightest_edges[i].weight;
709 size_t u = lightest_edges[i].from;
710 size_t v = lightest_edges[i].to;
711
712 if (weight == INFINITY) continue;
713
714 if (!gsl_matrix_get (spanning_tree, u, v)) {
715 min_weight += weight;
716 gsl_matrix_set (spanning_tree, u, v, weight);
717 gsl_matrix_set (spanning_tree, v, u, weight);
718 }
719
720 // Do the join
721 if (parent_components[u] != parent_components[v]) {
722 number_of_components -= 1;
723 size_t component_to_remove = parent_components[v];
724 for (size_t j = 0; j < n; j++) {
725 if (parent_components[j] == component_to_remove) {
726 parent_components[j] = parent_components[u];
727 }
728 }
729 }
730 }
731 }
732
733 printf ("MINIMUM_SPANNING_TREE_WEIGHTS:\n");
734 print_gsl_matrix (spanning_tree);
735 printf ("TOTAL_WEIGHT: %.0lf\n", min_weight);
736 printf ("ITERATION_COUNT: %zu\n", count);
737
738 return spanning_tree;
739}
740
741void
742prufer_code (gsl_matrix *spanning_tree_matrix)
743{
744 size_t n = spanning_tree_matrix->size1;
745
746 gsl_matrix *tree = gsl_matrix_alloc (n, n);
747 gsl_matrix_memcpy (tree, spanning_tree_matrix);
748 struct {
749 size_t *items;
750 size_t count;
751 size_t capacity;
752 } prufer = {0};
753 struct {
754 size_t *items;
755 size_t count;
756 size_t capacity;
757 } weights = {0};
758
759 for (size_t i = 0; i < n - 1; ++i) {
760 // Find hanging vertex with the lowest number
761 size_t v, u;
762 for (size_t j = 0; j < n; ++j) {
763 size_t deg = 0;
764 for (size_t k = 0; k < n; ++k) {
765 if (gsl_matrix_get (tree, j, k) > 0) {
766 deg += 1;
767 u = k;
768 }
769 }
770
771 if (deg == 1) {
772 v = j;
773 break;
774 }
775 }
776
777 // Encode the only vertex neighbouring `v'
778 DYNAMIC_ARRAY_APPEND (prufer, u);
779 DYNAMIC_ARRAY_APPEND (weights, gsl_matrix_get (tree, u, v));
780
781 // "Pop"
782 gsl_matrix_set (tree, u, v, 0);
783 gsl_matrix_set (tree, v, u, 0);
784 }
785
786 printf ("MINIMAL_SPANNING_TREE:\n");
787 print_gsl_matrix (spanning_tree_matrix);
788
789 printf ("PRUFER_CODE: ");
790 DYNAMIC_ARRAY_FOREACH (p, prufer)
791 printf ("%zu ", *p);
792 printf ("\n");
793
794 printf ("SAVED_WEIGHTS: ");
795 DYNAMIC_ARRAY_FOREACH (w, weights)
796 printf ("%zu ", *w);
797 printf ("\n");
798
799 // Decoding
800 gsl_matrix *decoded_tree = gsl_matrix_calloc (n, n);
801
802 struct {
803 size_t *items;
804 size_t count;
805 size_t capacity;
806 } not_used_vertices = {0};
807 for (size_t i = 0; i < n; ++i)
808 DYNAMIC_ARRAY_APPEND (not_used_vertices, i);
809
810 for (size_t i = 0; i < n - 1; ++i) {
811 // Picking unused vertex v with the lowest number not in the rest
812 // of the Prufer code
813 size_t v;
814 for (size_t j = 0; j < not_used_vertices.count; ++j) {
815 bool met = false;
816 for (size_t k = i; k < n - 1; ++k) {
817 if (not_used_vertices.items[j] == prufer.items[k]) {
818 met = true;
819 break;
820 }
821 }
822
823 if (!met) {
824 v = not_used_vertices.items[j];
825
826 // Remove now used
827 DYNAMIC_ARRAY_ERASE (not_used_vertices, j);
828 break;
829 }
830 }
831
832 // Add edge
833 gsl_matrix_set (decoded_tree, v, prufer.items[i], weights.items[i]);
834 gsl_matrix_set (decoded_tree, prufer.items[i], v, weights.items[i]);
835 }
836
837 printf ("DECODED_MINIMAL_SPANNING_TREE:\n");
838 print_gsl_matrix (decoded_tree);
839
840 for (size_t i = 0; i < n; ++i) {
841 for (size_t j = 0; j < n; ++j) {
842 if (gsl_matrix_get (spanning_tree_matrix, i, j) !=
843 gsl_matrix_get (decoded_tree, i, j)) {
844 printf ("Error, matrices are not the same!\n");
845 return;
846 }
847 }
848 }
849 printf("Success, matrices the same!\n");
850
851 gsl_matrix_free (tree);
852 gsl_matrix_free (decoded_tree);
853}
854
855bool
856is_graph_eulerian (GRAPH g)
857{
858 size_t n = g->vertex_count;
859
860 if (n <= 2)
861 return false;
862
863 // Check if degree of all vertices is even
864 for (size_t i = 0; i < n; ++i) {
865 size_t degree = 0;
866 for (size_t j = 0; j < n; ++j) {
867 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
868 gsl_matrix_get (g->adjecency_matrix, j, i))
869 degree += 1;
870 }
871
872 if (degree % 2 != 0)
873 return false;
874 }
875
876 return true;
877}
878
879// https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG12.pdf
880// page 33
881bool
882is_graph_hamiltonian (GRAPH g)
883{
884 size_t n = g->vertex_count;
885
886 // Find neighbours
887 struct {
888 size_t *items;
889 size_t count;
890 size_t capacity;
891 } neighbours[MAX_VERTEX_COUNT] = {0};
892 for (size_t i = 0; i < n; ++i) {
893 for (size_t j = 0; j < n; ++j) {
894 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
895 gsl_matrix_get (g->adjecency_matrix, j, i)) {
896 DYNAMIC_ARRAY_APPEND (neighbours[i], j);
897 }
898 }
899 }
900
901 struct {
902 size_t *items;
903 size_t count;
904 size_t capacity;
905 } not_visited_neighbours[MAX_VERTEX_COUNT] = {0};
906
907 struct {
908 size_t *items;
909 size_t count;
910 size_t capacity;
911 } path = {0};
912
913 size_t a = 0;
914 DYNAMIC_ARRAY_APPEND (path, a);
915 DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[a], neighbours[a]);
916
917 while (path.count) {
918 size_t x = path.items[path.count - 1];
919
920 if (not_visited_neighbours[x].count) {
921 size_t y = not_visited_neighbours[x].items[not_visited_neighbours[x].count - 1];
922 not_visited_neighbours[x].count -= 1;
923
924 bool y_in_path = false;
925 DYNAMIC_ARRAY_FOREACH(p, path) {
926 if (*p == y) {
927 y_in_path = true;
928 break;
929 }
930 }
931
932 if (!y_in_path) {
933 DYNAMIC_ARRAY_APPEND (path, y);
934 DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[y], neighbours[y]);
935 if (path.count == n &&
936 (gsl_matrix_get (g->adjecency_matrix, a, y) ||
937 gsl_matrix_get (g->adjecency_matrix, y, a))) {
938 return true;
939 }
940 }
941 } else {
942 path.count -= 1; // pop back
943 }
944 }
945
946 return false;
947}
948
949void
950graph_ensure_eulerian (GRAPH g)
951{
952 size_t n = g->vertex_count;
953
954 if (n <= 2) {
955 printf ("Not enough vertices for an Euler cycle (<3)\n");
956 return;
957 }
958
959 if (is_graph_eulerian (g)) {
960 printf ("Graph is Eulerian, no modifications needed\n");
961 } else {
962 // Find vertices with odd degrees
963 struct {
964 size_t *items;
965 size_t count;
966 size_t capacity;
967 } odd_degree_vertices = {0};
968 for (size_t i = 0; i < n; ++i) {
969 size_t degree = 0;
970 for (size_t j = 0; j < n; ++j) {
971 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
972 gsl_matrix_get (g->adjecency_matrix, j, i))
973 degree += 1;
974 }
975 if (degree % 2 != 0)
976 DYNAMIC_ARRAY_APPEND (odd_degree_vertices, i);
977 }
978
979 size_t first;
980
981 // Join vertices with odd degrees
982 add_edge:
983 if (odd_degree_vertices.count)
984 first = odd_degree_vertices.items[0];
985
986 // Find pair
987 for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) {
988 size_t second = odd_degree_vertices.items[second_index];
989
990 // Help keep acyclic
991 size_t i = first < second ? first : second;
992 size_t j = first > second ? first : second;
993
994 // Add edge if there isn't
995 if (gsl_matrix_get (g->adjecency_matrix, i, j) == 0 &&
996 gsl_matrix_get (g->adjecency_matrix, j, i) == 0) {
997 double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1;
998 double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1;
999 graph_edge_set (g, i, j, new_weight, new_capacity);
1000
1001 printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight);
1002
1003 // Update
1004 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index);
1005 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0);
1006
1007 goto add_edge;
1008 }
1009 }
1010
1011 // If edge addition helped only partially, delete edges
1012 remove_edge:
1013 if (odd_degree_vertices.count)
1014 first = odd_degree_vertices.items[0];
1015
1016 for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) {
1017 size_t second = odd_degree_vertices.items[second_index];
1018
1019 size_t i = first < second ? first : second;
1020 size_t j = first > second ? first : second;
1021
1022 // Don't delete edge if it will make graph unconnected
1023 size_t degree_i = 0;
1024 size_t degree_j = 0;
1025 for (size_t k = 0; k < n; ++k) {
1026 if (gsl_matrix_get (g->adjecency_matrix, i, k) ||
1027 gsl_matrix_get (g->adjecency_matrix, k, i))
1028 degree_i += 1;
1029 if (gsl_matrix_get (g->adjecency_matrix, j, k) ||
1030 gsl_matrix_get (g->adjecency_matrix, k, j))
1031 degree_j += 1;
1032 }
1033
1034 if (degree_i == 1 &&
1035 degree_j == 1)
1036 continue;
1037
1038 gsl_matrix_set (g -> adjecency_matrix, i, j, 0);
1039 gsl_matrix_set (g -> weight_matrix, i, j, 0);
1040 gsl_matrix_set (g -> capacity_matrix, i, j, 0);
1041 gsl_matrix_set (g -> adjecency_matrix, j, i, 0);
1042 gsl_matrix_set (g -> weight_matrix, j, i, 0);
1043 gsl_matrix_set (g -> capacity_matrix, j, i, 0);
1044
1045 printf ("Removed edge: %zu -> %zu\n", i, j);
1046
1047 // Update
1048 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index);
1049 DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0);
1050
1051 goto remove_edge;
1052 }
1053
1054 if (odd_degree_vertices.count)
1055 printf ("Unable to make graph Eulerian\n");
1056
1057 printf ("ADJECENCY_MATRIX:\n");
1058 print_gsl_matrix (g->adjecency_matrix);
1059 }
1060
1061 // Find Euler cycles
1062
1063 // Find neighbours
1064 struct {
1065 size_t *items;
1066 size_t count;
1067 size_t capacity;
1068 } neighbours[MAX_VERTEX_COUNT] = {0};
1069 for (size_t i = 0; i < n; ++i) {
1070 for (size_t j = 0; j < n; ++j) {
1071 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1072 gsl_matrix_get (g->adjecency_matrix, j, i)) {
1073 DYNAMIC_ARRAY_APPEND (neighbours[i], j);
1074 }
1075 }
1076 }
1077
1078 // https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG12.pdf
1079 // Page 27
1080 struct {
1081 size_t *items;
1082 size_t count;
1083 size_t capacity;
1084 } euler_cycle = {0};
1085 struct {
1086 size_t *items;
1087 size_t count;
1088 size_t capacity;
1089 } s = {0};
1090 DYNAMIC_ARRAY_APPEND (s, 0);
1091
1092 while (s.count) {
1093 size_t v = s.items[s.count - 1];
1094
1095 if (!neighbours[v].count) {
1096 s.count -= 1;
1097 DYNAMIC_ARRAY_APPEND (euler_cycle, v);
1098 } else {
1099 size_t u = neighbours[v].items[0];
1100 DYNAMIC_ARRAY_APPEND (s, u);
1101
1102 // Removing
1103 DYNAMIC_ARRAY_ERASE (neighbours[v], 0);
1104 for (size_t i = 0; i < neighbours[u].count; ++i) {
1105 if (neighbours[u].items[i] == v) {
1106 DYNAMIC_ARRAY_ERASE (neighbours[u], i);
1107 i -= 1;
1108 }
1109 }
1110 }
1111 }
1112
1113 printf ("EULER_CYCLE: ");
1114 DYNAMIC_ARRAY_FOREACH (vertex, euler_cycle) {
1115 if (vertex != euler_cycle.items)
1116 printf (" -> ");
1117 printf ("%zu", *vertex);
1118 } printf ("\n");
1119 DYNAMIC_ARRAY_APPEND (euler_cycle, n);
1120 free (g->highlighted_path);
1121 g->highlighted_path = euler_cycle.items;
1122
1123 for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i)
1124 DYNAMIC_ARRAY_FREE (neighbours[i]);
1125 DYNAMIC_ARRAY_FREE (s);
1126 // DYNAMIC_ARRAY_FREE (euler_cycle);
1127}
1128
1129void
1130graph_ensure_hamiltonian (GRAPH g)
1131{
1132 size_t n = g->vertex_count;
1133
1134 if (n <= 2) {
1135 printf ("Not enough vertices for an Hamilton cycle (<3)\n");
1136 return;
1137 }
1138
1139 if (is_graph_hamiltonian (g)) {
1140 printf ("Graph is Hamiltonian, no modifications needed\n");
1141 } else {
1142 struct {
1143 struct vertex_degree {
1144 size_t vertex;
1145 size_t degree;
1146 } *items;
1147 size_t count;
1148 size_t capacity;
1149 } vertex_degree_pairs = {0};
1150 for (size_t i = 0; i < n; ++i) {
1151 size_t degree = 0;
1152 for (size_t j = 0; j < n; ++j) {
1153 if (gsl_matrix_get (g->adjecency_matrix, i, j) ||
1154 gsl_matrix_get (g->adjecency_matrix, j, i))
1155 degree += 1;
1156 }
1157
1158 DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {i, degree}));
1159 }
1160
1161 // Add edges to vertices with low degree
1162 do {
1163 size_t min_idx = 0;
1164 for (size_t i = 1; i < n; ++i) {
1165 if (vertex_degree_pairs.items[i].degree <
1166 vertex_degree_pairs.items[min_idx].degree)
1167 min_idx = i;
1168 }
1169
1170 size_t vertex1 = vertex_degree_pairs.items[min_idx].vertex;
1171 size_t degree1 = vertex_degree_pairs.items[min_idx].degree;
1172 DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx);
1173
1174 for (size_t k = 0; k < n; ++k) {
1175 size_t min_idx = 0;
1176 for (size_t i = 1; i < n; ++i) {
1177 if (vertex_degree_pairs.items[min_idx].vertex != vertex1 &&
1178 vertex_degree_pairs.items[i].degree <
1179 vertex_degree_pairs.items[min_idx].degree)
1180 min_idx = i;
1181 }
1182 size_t vertex2 = vertex_degree_pairs.items[min_idx].vertex;
1183 size_t degree2 = vertex_degree_pairs.items[min_idx].degree;
1184
1185 if (!gsl_matrix_get (g->adjecency_matrix, vertex1, vertex2) &&
1186 !gsl_matrix_get (g->adjecency_matrix, vertex2, vertex1)) {
1187 size_t i = vertex1 < vertex2 ? vertex1 : vertex2;
1188 size_t j = vertex1 > vertex2 ? vertex1 : vertex2;
1189
1190 double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1;
1191 double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1;
1192 graph_edge_set (g, i, j, new_weight, new_capacity);
1193
1194 printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight);
1195
1196 DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx);
1197 DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex2, degree2 + 1}));
1198 break;
1199 }
1200 }
1201
1202 DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex1, degree1 + 1}));
1203 } while (!is_graph_hamiltonian(g));
1204 }
1205
1206 find_hamiltonian_cycles (g);
1207}
1208
1209struct path {
1210 size_t *items;
1211 size_t count;
1212 size_t capacity;
1213} typedef *PATH;
1214
1215void
1216find_hamiltonian_recursive (GRAPH g, FILE *fd, size_t *cycle_count,
1217 size_t start, PATH path,
1218 double path_weight, PATH min_path,
1219 double *min_path_weight)
1220{
1221 if (*cycle_count >= 1000000)
1222 return;
1223
1224 // Path is built
1225 if (path->count == g->vertex_count) {
1226 size_t last = path->items[path->count - 1];
1227 if (gsl_matrix_get (g->adjecency_matrix, last, start) ||
1228 gsl_matrix_get (g->adjecency_matrix, start, last)) {
1229 *cycle_count += 1;
1230
1231 path_weight +=
1232 gsl_matrix_get (g->weight_matrix, start, last) +
1233 gsl_matrix_get (g->weight_matrix, last, start);
1234 DYNAMIC_ARRAY_APPEND (*path, start);
1235 if (*min_path_weight > path_weight) {
1236 DYNAMIC_ARRAY_COPY_OTHER (*min_path, *path);
1237 *min_path_weight = path_weight;
1238 }
1239
1240 for (size_t i = 0; i < path->count; ++i)
1241 fprintf (fd, "%zu ", path->items[i]);
1242 fprintf (fd, "@ %.0lf\n", path_weight);
1243 path->count -= 1;
1244 }
1245 return;
1246 }
1247
1248 // Continue building
1249 for (size_t i = 0; i < g->vertex_count; ++i) {
1250 size_t last = path->items[path->count - 1];
1251 if (!gsl_matrix_get (g->adjecency_matrix, last, i) &&
1252 !gsl_matrix_get (g->adjecency_matrix, i, last))
1253 continue;
1254
1255 bool used = false;
1256 DYNAMIC_ARRAY_FOREACH (v, *path) {
1257 if (*v == i) {
1258 used = true;
1259 break;
1260 }
1261 } if (used) continue;
1262
1263 double new_weight = path_weight
1264 + gsl_matrix_get (g->weight_matrix, last, i)
1265 + gsl_matrix_get (g->weight_matrix, i, last);
1266 DYNAMIC_ARRAY_APPEND (*path, i);
1267 find_hamiltonian_recursive (g, fd, cycle_count, start, path, new_weight, min_path, min_path_weight);
1268 path->count -= 1;
1269 }
1270}
1271
1272void
1273find_hamiltonian_cycles (GRAPH g)
1274{
1275 const char *filename = "hamiltonian-cycles.txt";
1276
1277 if (g->vertex_count > 20) {
1278 printf ("Graph is too large (>20v), iterative algorithm will take too long\n");
1279 return;
1280 }
1281
1282 FILE *fd = fopen (filename, "w+");
1283
1284
1285 struct path path = {0};
1286 struct path min_path = {0};
1287 size_t cycle_count = 0;
1288 double min_path_weight = INFINITY;
1289 for (size_t i = 0; i < g->vertex_count; ++i) {
1290 DYNAMIC_ARRAY_RESET (path);
1291 DYNAMIC_ARRAY_APPEND (path, i);
1292 find_hamiltonian_recursive (g, fd, &cycle_count, i, &path, 0, &min_path, &min_path_weight);
1293 }
1294
1295 fclose (fd);
1296
1297 printf ("CYCLES_TOTAL: %zu\n", cycle_count);
1298 printf ("All cycles are saved here: %s\n", filename);
1299 printf ("Cycle with minimum weight (%.0lf): ", min_path_weight);
1300 DYNAMIC_ARRAY_FOREACH (vertex, min_path) {
1301 if (vertex != min_path.items)
1302 printf (" -> ");
1303 printf ("%zu", *vertex);
1304 } printf ("\n");
1305 DYNAMIC_ARRAY_APPEND (min_path, g->vertex_count);
1306 free (g->highlighted_path);
1307 g->highlighted_path = min_path.items;
1308
1309
1310 DYNAMIC_ARRAY_FREE (path);
1311}
diff --git a/src/graph.h b/src/graph.h
new file mode 100644
index 0000000..f55e975
--- /dev/null
+++ b/src/graph.h
@@ -0,0 +1,71 @@
1#ifndef INCLUDED_GRAPH_H
2#define INCLUDED_GRAPH_H
3
4#include <stdlib.h>
5#include <stdbool.h>
6#include <gsl/gsl_matrix.h>
7#include <raylib.h>
8#include "distribution.h"
9
10enum graph_type {
11 GRAPH_TYPE_NONE,
12 GRAPH_TYPE_POSITIVE = 1 << 0,
13 GRAPH_TYPE_NEGATIVE = 1 << 1,
14 GRAPH_TYPE_POSITIVE_NEGATIVE = GRAPH_TYPE_POSITIVE | GRAPH_TYPE_NEGATIVE,
15};
16
17struct edge {
18 size_t from;
19 size_t to;
20};
21
22struct edges {
23 struct edge *items;
24 size_t count;
25 size_t capacity;
26};
27
28typedef struct graph {
29 enum graph_type type;
30 size_t vertex_count;
31 gsl_matrix *adjecency_matrix;
32 gsl_matrix *weight_matrix;
33 gsl_matrix *capacity_matrix;
34 size_t *highlighted_path;
35 struct edges highlighted_edges;
36} *GRAPH;
37
38void generate_graph (GRAPH, DISTRIBUTION,
39 size_t vertex_count, enum graph_type);
40void graph_unhighlight (GRAPH g);
41void graph_edge_set (GRAPH, size_t from, size_t to,
42 double weight, double capacity);
43void print_graph (GRAPH);
44void highlight_graph (GRAPH, const gsl_matrix *);
45
46// lab 1
47gsl_matrix *shimbell_method (GRAPH, size_t edge_count, bool max);
48size_t graph_count_routes (GRAPH, size_t from, size_t to);
49
50// lab 2
51size_t *dijkstra_positive (GRAPH, size_t from, size_t to, bool max);
52size_t *floyd_warshall (GRAPH, size_t from, size_t to, bool max);
53
54// lab 3
55double max_flow_ford_fulkerson (GRAPH, size_t from, size_t to);
56double min_cost_flow (GRAPH, size_t from, size_t to, double required_flow);
57
58// lab 4
59size_t count_spanning_trees (GRAPH);
60gsl_matrix *min_weight_spannig_tree_prim (GRAPH);
61gsl_matrix *min_weight_spannig_tree_boruvka (GRAPH);
62void prufer_code (gsl_matrix *);
63
64// lab 5
65bool is_graph_eulerian (GRAPH);
66bool is_graph_hamiltonian (GRAPH);
67void graph_ensure_eulerian (GRAPH);
68void graph_ensure_hamiltonian (GRAPH);
69void find_hamiltonian_cycles (GRAPH);
70
71#endif
diff --git a/src/main.c b/src/main.c
new file mode 100644
index 0000000..d297e72
--- /dev/null
+++ b/src/main.c
@@ -0,0 +1,580 @@
1#define _GNU_SOURCE
2#include <stdlib.h>
3#include <string.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <assert.h>
7#include <time.h>
8#include <math.h>
9#include <limits.h>
10#include <raylib.h>
11#include <raymath.h>
12#include <gsl/gsl_matrix.h>
13#include <gsl/gsl_blas.h>
14#include <gsl/gsl_eigen.h>
15#include <gsl/gsl_sort_vector.h>
16
17#include "config.h"
18#include "utils.h"
19#include "distribution.h"
20#include "graph.h"
21#include "dynamic-array.h"
22
23#define BUTTONS(X, ...) \
24 X(__VA_ARGS__, EDIT, "Edit edge" ) \
25 X(__VA_ARGS__, NEW_POSITIVE, "New graph+" ) \
26 X(__VA_ARGS__, NEW_POSITIVE_NEGATIVE, "New graph±" ) \
27 X(__VA_ARGS__, ROUTE_COUNT, "Route count" ) \
28 X(__VA_ARGS__, SHIMBELL_MIN, "Min Shimbell" ) \
29 X(__VA_ARGS__, SHIMBELL_MAX, "Max Shimbell" ) \
30 X(__VA_ARGS__, DIJKSTRA_POSITIVE_MIN, "Min Dijkstra+" ) \
31 X(__VA_ARGS__, DIJKSTRA_POSITIVE_MAX, "Max Dijkstra+" ) \
32 X(__VA_ARGS__, FLOYD_WARSHALL_MIN, "Min Floyd-Warshall" ) \
33 X(__VA_ARGS__, FLOYD_WARSHALL_MAX, "Max Floyd-Warshall" ) \
34 X(__VA_ARGS__, MAX_FLOW_FORD_FULKERSON, "Max flow Ford-Fulkerson" ) \
35 X(__VA_ARGS__, MIN_COST_FLOW, "Min cost flow" ) \
36 X(__VA_ARGS__, COUNT_SPANNING_TREES, "Count spanning trees" ) \
37 X(__VA_ARGS__, MIN_WEIGHT_SPANNIG_TREE_PRIM, "Min weight spanning tree Prim" ) \
38 X(__VA_ARGS__, MIN_WEIGHT_SPANNIG_TREE_BORUVKA, "Min weight spanning tree Borůvka") \
39 X(__VA_ARGS__, ENSURE_EULERIAN, "Ensure Eulerian" ) \
40 X(__VA_ARGS__, ENSURE_HAMILTONIAN, "Ensure Hamiltonian" ) \
41
42#define ENUM_ENTRY(PREFIX, SYMBOL, ...) PREFIX##_##SYMBOL,
43#define ENUM_ENTRY_VALUE(PREFIX, SYMBOL, VALUE, ...) [PREFIX##_##SYMBOL] = VALUE,
44
45enum {
46 BUTTONS(ENUM_ENTRY, BUTTON)
47 BUTTON_COUNT
48} button;
49#define BUTTON_NONE BUTTON_COUNT
50
51static const char *button_labels[] = {
52 BUTTONS(ENUM_ENTRY_VALUE, BUTTON)
53};
54
55static Font font;
56static Rectangle button_recs[BUTTON_COUNT];
57static int button_hover = BUTTON_NONE;
58static bool button_pressed = false;
59static double start_time;
60static Vector2 *model_vertices = NULL;
61static struct distribution dist = {0};
62static struct graph g = {0};
63static gsl_matrix *saved_adjecency_matrix = NULL;
64static gsl_matrix *saved_weight_matrix = NULL;
65static gsl_matrix *saved_capacity_matrix = NULL;
66
67void
68new_graph (size_t vertex_count, enum graph_type type)
69{
70 distribution_init (&dist, DIST_N*vertex_count, DIST_B, DIST_R, DIST_C);
71 generate_graph (&g, &dist, vertex_count, type);
72 print_graph (&g);
73 start_time = GetTime ();
74
75 // Initialize vertex positions in a circle
76 model_vertices = realloc (model_vertices, vertex_count*(sizeof *model_vertices));
77 for (size_t i = 0; i < vertex_count; ++i) {
78 model_vertices[i].x = cosf (PI + 2*PI*i/(float)vertex_count);
79 model_vertices[i].y = sinf (PI + 2*PI*i/(float)vertex_count);
80 }
81
82 // Print graph in dot format
83 // puts ("digraph G {");
84 // for (int i = 0; i < vertex_count; i++) {
85 // for (int j = 0; j < vertex_count; j++) {
86 // if (gsl_matrix_get (m, i, j) == 0)
87 // continue;
88 // printf (" %d -> %d [label=\"%g\"]\n", i, j, gsl_matrix_get (m, i, j));
89 // }
90 // } puts ("}");
91}
92
93void
94startup (void)
95{
96 SetConfigFlags (FLAG_MSAA_4X_HINT |
97 FLAG_WINDOW_RESIZABLE |
98 FLAG_VSYNC_HINT |
99 FLAG_WINDOW_UNDECORATED);
100 InitWindow (INITIAL_SCREEN_WIDTH, INITIAL_SCREEN_HEIGHT, WINDOW_TITLE);
101 SetTargetFPS (60);
102
103 const int codepoints_count = 96 + 256 + 2;
104 int codepoints[codepoints_count];
105 for (int i = 0; i < 95; i++) codepoints[ 0 + i] = 0x0020 + i;
106 for (int i = 0; i < 255; i++) codepoints[96 + i] = 0x0400 + i;
107 codepoints[codepoints_count - 2] = 0x16f;
108 codepoints[codepoints_count - 1] = 0x0b1;
109
110 font = LoadFontEx ("./res/iosevka-term-slab-regular.ttf", FONT_SIZE, codepoints, codepoints_count);
111 SetTextureFilter (font.texture, TEXTURE_FILTER_ANISOTROPIC_16X);
112
113 // srand (time (NULL));
114 srand (4);
115
116 // Initialize buttons
117 for (int i = 0; i < BUTTON_COUNT; ++i) {
118 Rectangle rec = {
119 .x = PADDING,
120 .y = PADDING + i*(BUTTON_HEIGHT + PADDING),
121 .width = BUTTON_WIDTH,
122 .height = BUTTON_HEIGHT,
123 };
124 button_recs[i] = rec;
125 }
126
127 start_time = GetTime ();
128
129 new_graph (INITIAL_VERTEX_COUNT, GRAPH_TYPE_POSITIVE);
130}
131
132static inline size_t
133read_vertex (char *label)
134{
135 size_t v;
136 for (;;) {
137 prompt (label, "%zu", &v);
138 if (v >= g.vertex_count) {
139 printf ("ERROR: Vertex out of range [0; %zu)!\n", g.vertex_count);
140 } else return v;
141 }
142}
143
144static inline size_t
145read_vertex_count (void)
146{
147 size_t vertex_count;
148 for (;;) {
149 prompt ("VERTEX_COUNT", "%zu", &vertex_count);
150 if (vertex_count > MAX_VERTEX_COUNT) {
151 printf ("ERROR: Vertex count cannot be larger than %zu!\n", MAX_VERTEX_COUNT);
152 } else return vertex_count;
153 }
154}
155
156static inline void
157handle_buttons (void)
158{
159 button_hover = BUTTON_NONE;
160 button_pressed = false;
161 for (int i = 0; i < BUTTON_COUNT; ++i) {
162 if (CheckCollisionPointRec (GetMousePosition (), button_recs[i])) {
163 button_hover = i;
164 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
165 button_pressed = true;
166 break;
167 }
168 }
169 if (button_pressed) {
170 if (button_hover != BUTTON_NONE) {
171 graph_unhighlight (&g);
172 if (saved_adjecency_matrix) {
173 gsl_matrix_free (g.adjecency_matrix);
174 g.adjecency_matrix = saved_adjecency_matrix;
175 saved_adjecency_matrix = NULL;
176 start_time = GetTime ();
177 }
178 if (saved_weight_matrix) {
179 gsl_matrix_free (g.weight_matrix);
180 g.weight_matrix = saved_weight_matrix;
181 saved_weight_matrix = NULL;
182 }
183 if (saved_capacity_matrix) {
184 gsl_matrix_free (g.capacity_matrix);
185 g.capacity_matrix = saved_capacity_matrix;
186 saved_capacity_matrix = NULL;
187 }
188 }
189 switch (button_hover) {
190 case BUTTON_EDIT: {
191 size_t from = read_vertex ("FROM");
192 size_t to = read_vertex ("TO");
193 if (to == from) {
194 printf("ERROR: Self-loops are not allowed!\n");
195 break;
196 }
197
198 double weight;
199 for (;;) {
200 prompt ("WEIGHT", "%lf", &weight);
201 if (weight > MAX_WEIGHT) {
202 printf ("ERROR: Weight cannot be larger than %lf!\n", MAX_WEIGHT);
203 } else if (g.type == GRAPH_TYPE_POSITIVE && weight < 0) {
204 printf ("ERROR: Weight cannot be negative in a positive graph!\n");
205 } else if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE && weight < -MAX_WEIGHT) {
206 printf ("ERROR: Weight cannot be less than %lf!\n", -MAX_WEIGHT);
207 } else break;
208 }
209
210 double capacity;
211 for (;;) {
212 prompt ("CAPACITY", "%lf", &capacity);
213 if (weight > MAX_WEIGHT) {
214 printf ("ERROR: Capacity cannot be larger than %lf!\n", MAX_CAPACITY);
215 } else break;
216 }
217
218 graph_unhighlight (&g);
219 graph_edge_set (&g, from, to, weight, capacity);
220 print_graph (&g);
221 } break;
222
223 case BUTTON_NEW_POSITIVE: {
224 new_graph (read_vertex_count (), GRAPH_TYPE_POSITIVE);
225 } break;
226
227 case BUTTON_NEW_POSITIVE_NEGATIVE: {
228 new_graph (read_vertex_count (), GRAPH_TYPE_POSITIVE_NEGATIVE);
229 } break;
230
231 case BUTTON_ROUTE_COUNT: {
232 size_t from = read_vertex ("FROM");
233 size_t to = read_vertex ("TO");
234 size_t routes = graph_count_routes (&g, from, to);
235 if (routes) printf ("ROUTE COUNT FROM %zu TO %zu: %zu\n", from, to, routes);
236 else printf ("NO ROUTES FROM %zu TO %zu\n", from, to);
237 } break;
238
239 case BUTTON_SHIMBELL_MIN: {
240 int edge_count = 0;
241 do {
242 printf ("SHIMBELL METHOD EDGE COUNT: ");
243 scanf ("%d", &edge_count);
244 while (getchar () != '\n');
245 } while (!edge_count);
246 gsl_matrix *sh = shimbell_method (&g, edge_count, false);
247 puts ("PATH MATRIX:");
248 print_gsl_matrix (sh);
249 gsl_matrix_free (sh);
250 } break;
251
252 case BUTTON_SHIMBELL_MAX: {
253 int edge_count = 0;
254 do {
255 printf ("SHIMBELL METHOD EDGE COUNT: ");
256 scanf ("%d", &edge_count);
257 while (getchar () != '\n');
258 } while (!edge_count);
259 gsl_matrix *sh = shimbell_method (&g, edge_count, true);
260 puts ("PATH MATRIX:");
261 print_gsl_matrix (sh);
262 gsl_matrix_free (sh);
263 } break;
264
265 case BUTTON_DIJKSTRA_POSITIVE_MIN: {
266 size_t from = read_vertex ("FROM");
267 size_t to = read_vertex ("TO");
268 g.highlighted_path = dijkstra_positive (&g, from, to, false);
269 } break;
270
271 case BUTTON_DIJKSTRA_POSITIVE_MAX: {
272 size_t from = read_vertex ("FROM");
273 size_t to = read_vertex ("TO");
274 g.highlighted_path = dijkstra_positive (&g, from, to, true);
275 } break;
276
277 case BUTTON_FLOYD_WARSHALL_MIN: {
278 size_t from = read_vertex ("FROM");
279 size_t to = read_vertex ("TO");
280 g.highlighted_path = floyd_warshall (&g, from, to, false);
281 } break;
282
283 case BUTTON_FLOYD_WARSHALL_MAX: {
284 size_t from = read_vertex ("FROM");
285 size_t to = read_vertex ("TO");
286 g.highlighted_path = floyd_warshall (&g, from, to, true);
287 } break;
288
289 case BUTTON_MAX_FLOW_FORD_FULKERSON: {
290 size_t from = read_vertex ("FROM");
291 size_t to = read_vertex ("TO");
292 double max_flow = max_flow_ford_fulkerson (&g, from, to);
293 printf ("MAX_FLOW: %.0lf\n", max_flow);
294 } break;
295
296 case BUTTON_MIN_COST_FLOW: {
297 size_t from = read_vertex ("FROM");
298 size_t to = read_vertex ("TO");
299 double max_flow = max_flow_ford_fulkerson(&g, from, to);
300 if (max_flow == 0) {
301 printf ("NO PATH FROM %zu TO %zu\n", from, to);
302 break;
303 }
304 double required_flow = floor (max_flow*2/3);
305 printf ("REQUIRED_FLOW: [%.0lf*2/3] = %.0lf\n", max_flow, required_flow);
306
307 double min_cost = min_cost_flow (&g, from, to, required_flow);
308 printf ("MIN_COST: %.0lf\n", min_cost);
309 } break;
310
311 case BUTTON_COUNT_SPANNING_TREES: {
312 double spannig_tree_count = count_spanning_trees (&g);
313 printf ("SPANNING TREE COUNT %.0lf\n", spannig_tree_count);
314 } break;
315
316 case BUTTON_MIN_WEIGHT_SPANNIG_TREE_PRIM: {
317 gsl_matrix *minimal_spanning_tree = min_weight_spannig_tree_prim (&g);
318 prufer_code (minimal_spanning_tree);
319 highlight_graph (&g, minimal_spanning_tree);
320 gsl_matrix_free (minimal_spanning_tree);
321 } break;
322
323 case BUTTON_MIN_WEIGHT_SPANNIG_TREE_BORUVKA: {
324 gsl_matrix *minimal_spanning_tree = min_weight_spannig_tree_boruvka (&g);
325 prufer_code (minimal_spanning_tree);
326 highlight_graph (&g, minimal_spanning_tree);
327 gsl_matrix_free (minimal_spanning_tree);
328 } break;
329
330 case BUTTON_ENSURE_EULERIAN: {
331 saved_adjecency_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count);
332 gsl_matrix_memcpy (saved_adjecency_matrix, g.adjecency_matrix);
333 saved_weight_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count);
334 gsl_matrix_memcpy (saved_weight_matrix, g.weight_matrix);
335 saved_capacity_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count);
336 gsl_matrix_memcpy (saved_capacity_matrix, g.capacity_matrix);
337 graph_ensure_eulerian (&g);
338 start_time = GetTime ();
339 } break;
340
341 case BUTTON_ENSURE_HAMILTONIAN: {
342 saved_adjecency_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count);
343 gsl_matrix_memcpy (saved_adjecency_matrix, g.adjecency_matrix);
344 saved_weight_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count);
345 gsl_matrix_memcpy (saved_weight_matrix, g.weight_matrix);
346 saved_capacity_matrix = gsl_matrix_alloc (g.vertex_count, g.vertex_count);
347 gsl_matrix_memcpy (saved_capacity_matrix, g.capacity_matrix);
348 graph_ensure_hamiltonian (&g);
349 start_time = GetTime ();
350 } break;
351 default: break;
352 }
353 }
354}
355
356static inline void
357draw_buttons (void)
358{
359 for (int i = 0; i < BUTTON_COUNT; i++) {
360 DrawRectangleRec (button_recs[i], i == button_hover ? BUTTON_HOVER_COLOR
361 : BUTTON_COLOR);
362 DrawRectangleLinesEx (button_recs[i], 2, i == button_hover ? BUTTON_HOVER_OUTLINE_COLOR
363 : BUTTON_OUTLINE_COLOR);
364 Vector2 text_center = Vector2Scale (
365 MeasureTextEx (font, button_labels[i],
366 FONT_SIZE, TEXT_SPACING),
367 0.5);
368 Vector2 rect_center = {
369 .x = button_recs[i].x + button_recs[i].width/2,
370 .y = button_recs[i].y + button_recs[i].height/2 + 1,
371 };
372 DrawTextEx (font, button_labels[i], Vector2Subtract (rect_center,
373 text_center),
374 FONT_SIZE, TEXT_SPACING, i == button_hover ? BUTTON_TEXT_HOVER_COLOR
375 : BUTTON_TEXT_COLOR);
376 }
377}
378
379static inline void
380progress_model (void)
381{
382 size_t n = g.vertex_count;
383 Vector2 force_on_vertices[MAX_VERTEX_COUNT] = {0};
384 for (size_t i = 0; i < n; ++i) {
385 for (size_t j = 0; j < n; ++j) {
386 if (i == j)
387 continue;
388 Vector2 dir = Vector2Normalize (Vector2Subtract (model_vertices[j],
389 model_vertices[i]));
390 if (gsl_matrix_get (g.adjecency_matrix, i, j) ||
391 gsl_matrix_get (g.adjecency_matrix, j, i)) {
392 float distance = Vector2Distance (model_vertices[i],
393 model_vertices[j]);
394 float mag = MODEL_C_SPRING*logf (distance/MODEL_L);
395 force_on_vertices[i] = Vector2Add (force_on_vertices[i],
396 Vector2Scale (dir, mag));
397 } else {
398 float square_distance = Vector2DistanceSqr (model_vertices[j],
399 model_vertices[i]);
400 float mag = MODEL_C_REP/square_distance;
401 force_on_vertices[i] = Vector2Add (force_on_vertices[i],
402 Vector2Scale (dir, -mag));
403 }
404 }
405 }
406
407 float heat = exp ((-1 + MODEL_COOLING_FACTOR)*(GetTime () - start_time))/100;
408 for (int i = 0; i < n; ++i) {
409 model_vertices[i] = Vector2Add (model_vertices[i],
410 Vector2Scale (force_on_vertices[i], heat));
411 }
412}
413
414void
415draw_edges (Vector2 *vertex_screen_positions)
416{
417 size_t n = g.vertex_count;
418 for (size_t i = 0; i < n; ++i) {
419 for (size_t j = 0; j < n; ++j) {
420 if (!gsl_matrix_get (g.adjecency_matrix, i, j)) continue;
421 double capacity = gsl_matrix_get (
422 g.capacity_matrix, i, j);
423 float line_thickness = Remap (capacity, 0, MAX_CAPACITY, 4, 8);
424 float arrow_side = 3*line_thickness;
425 float arrow_height = arrow_side*sqrt (3)/2;
426
427 Vector2 dir = Vector2Normalize (Vector2Subtract (
428 vertex_screen_positions[j],
429 vertex_screen_positions[i]));
430
431 Vector2 line_offset = Vector2Scale (dir, 1.5*VERTEX_RADIUS);
432 Vector2 line_begin = Vector2Add (vertex_screen_positions[i],
433 line_offset);
434 Vector2 line_end = Vector2Subtract (
435 Vector2Subtract (vertex_screen_positions[j], line_offset),
436 Vector2Scale (dir, arrow_height));
437
438 double weight = gsl_matrix_get (g.weight_matrix, i, j);
439 float brightness = Remap (Normalize (fabs (weight), 0, MAX_WEIGHT),
440 0, 1, 0.25, 0.75);
441 Color line_color = ColorBrightness (BLACK, 1 - brightness);
442 if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE) {
443 if (weight < 0) {
444 line_color.b = 255/6;
445 line_color.g = 255/6;
446 } else {
447 line_color.r = 255/6;
448 line_color.b = 255/6;
449 }
450 }
451 if (g.highlighted_path) {
452 for (size_t v = 0; g.highlighted_path[v] != n; ++v) {
453 if (g.highlighted_path[v + 0] == i &&
454 g.highlighted_path[v + 1] == j ||
455 g.highlighted_path[v + 0] == j &&
456 g.highlighted_path[v + 1] == i) {
457 if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE) {
458 line_color = weight < 0 ? (Color) { 0xff, 0x00, 0x00, 0xff }
459 : (Color) { 0x00, 0xff, 0x00, 0xff };
460 } else {
461 line_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR;
462 } break;
463 }
464 }
465 } else if (g.highlighted_edges.count) {
466 for (size_t v = 0; v < g.highlighted_edges.count; ++v) {
467 if (g.highlighted_edges.items[v].from == i &&
468 g.highlighted_edges.items[v].to == j) {
469 if (g.type == GRAPH_TYPE_POSITIVE_NEGATIVE) {
470 line_color = weight < 0 ? (Color) { 0xff, 0x00, 0x00, 0xff }
471 : (Color) { 0x00, 0xff, 0x00, 0xff };
472 } else {
473 line_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR;
474 } break;
475 }
476 }
477 }
478
479 const Vector2 side = Vector2Scale (dir, -arrow_side/2);
480 DrawLineEx (line_begin, line_end, line_thickness, line_color);
481 DrawTriangle (
482 Vector2Add (line_end, Vector2Scale (dir, arrow_height)),
483 Vector2Add (line_end, Vector2Rotate (side, PI/2)),
484 Vector2Add (line_end, Vector2Rotate (side, -PI/2)),
485 line_color);
486
487 char *anot;
488 asprintf (&anot, "%.0lf/%.0lf", capacity, weight);
489 Vector2 center = Vector2Scale (
490 MeasureTextEx (font, anot, FONT_SIZE, TEXT_SPACING), 0.5);
491 Vector2 midpoint = Vector2Lerp(line_begin, line_end, 0.5);
492 Rectangle bounding_box = {
493 .x = midpoint.x - center.x - 4,
494 .y = midpoint.y - center.y,
495 .width = 2*(center.x + 4),
496 .height = 2*center.y,
497 };
498 DrawRectangleRounded(bounding_box, 0.5, 16, ColorAlpha (BACKGROUND_COLOR, 0.75));
499 DrawTextEx (font, anot,
500 Vector2Subtract (midpoint, center),
501 FONT_SIZE, TEXT_SPACING, EDGE_TEXT_COLOR);
502 free (anot);
503 }
504 }
505}
506
507void
508draw_vertices (Vector2 *vertex_screen_positions)
509{
510 for (size_t i = 0; i < g.vertex_count; ++i) {
511 Color outline_color = VERTEX_OUTLINE_COLOR;
512
513 if (g.highlighted_path) {
514 for (size_t v = 0; g.highlighted_path[v] != g.vertex_count; ++v) {
515 if (g.highlighted_path[v] == i)
516 outline_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR;
517 }
518 } else if (g.highlighted_edges.count) {
519 for (size_t v = 0; v < g.highlighted_edges.count; ++v) {
520 if (g.highlighted_edges.items[v].from == i ||
521 g.highlighted_edges.items[v].to == i) {
522 outline_color = VERTEX_OUTLINE_HIGHLIGHTED_COLOR;
523 }
524 }
525 }
526
527 DrawCircleV (vertex_screen_positions[i], 1.2*VERTEX_RADIUS, outline_color);
528 DrawCircleV (vertex_screen_positions[i], VERTEX_RADIUS, VERTEX_COLOR);
529 char *anot;
530 asprintf (&anot, "%zu", i);
531 Vector2 center = Vector2Scale (
532 MeasureTextEx (font, anot, FONT_SIZE, TEXT_SPACING),
533 0.5);
534 DrawTextEx (font, anot,
535 Vector2Subtract (vertex_screen_positions[i], center),
536 FONT_SIZE, TEXT_SPACING, VERTEX_TEXT_COLOR);
537 free (anot);
538 }
539}
540
541int
542main (void)
543{
544 startup ();
545 while (!WindowShouldClose ()) {
546 if (IsKeyDown (KEY_SPACE))
547 start_time = GetTime ();
548 handle_buttons ();
549 progress_model ();
550
551 // Find model space position supremums
552 Vector2 pos_max = { -INFINITY, -INFINITY };
553 Vector2 pos_min = { INFINITY, INFINITY };
554 for (size_t i = 0; i < g.vertex_count; ++i) {
555 if (model_vertices[i].x > pos_max.x) pos_max.x = model_vertices[i].x;
556 if (model_vertices[i].y > pos_max.y) pos_max.y = model_vertices[i].y;
557 if (model_vertices[i].x < pos_min.x) pos_min.x = model_vertices[i].x;
558 if (model_vertices[i].y < pos_min.y) pos_min.y = model_vertices[i].y;
559 }
560
561 // Remap model space positions to screen space
562 Vector2 vertex_screen_positions[g.vertex_count];
563 for (size_t i = 0; i < g.vertex_count; ++i) {
564 vertex_screen_positions[i] = (Vector2) {
565 .x = Remap (model_vertices[i].x, pos_min.x, pos_max.x, 2*VERTEX_RADIUS + BUTTON_WIDTH + PADDING, GetScreenWidth () - 2*VERTEX_RADIUS),
566 .y = Remap (model_vertices[i].y, pos_min.y, pos_max.y, 2*VERTEX_RADIUS, GetScreenHeight () - 2*VERTEX_RADIUS),
567 };
568 }
569
570 BeginDrawing ();
571 ClearBackground (BACKGROUND_COLOR);
572 draw_buttons ();
573 draw_edges (vertex_screen_positions);
574 draw_vertices (vertex_screen_positions);
575 // DrawFPS (2, 0);
576 EndDrawing ();
577 } CloseWindow ();
578
579 return EXIT_SUCCESS;
580}
diff --git a/src/utils.c b/src/utils.c
new file mode 100644
index 0000000..d96c3b6
--- /dev/null
+++ b/src/utils.c
@@ -0,0 +1,108 @@
1#include "utils.h"
2#include <stdio.h>
3
4void
5print_gsl_matrix (const gsl_matrix *m)
6{
7 int pad = 2;
8
9 for (size_t i = 0; i < log10sz (m->size1) + 3; i++)
10 putchar (' ');
11 for (size_t j = 0; j < m->size2; j++)
12 printf ("[%0*zu]", log10sz (m->size2) + 1 + pad, j);
13 putchar ('\n');
14 for (size_t i = 0; i < m->size1; i++) {
15 printf ("[%0*zu]", log10sz (m->size1) + 1, i);
16 for (size_t j = 0; j < m->size2; j++)
17 printf (" %*.0f ", log10sz (m->size2) + 1 + pad, gsl_matrix_get (m, i, j));
18 putchar ('\n');
19 }
20}
21
22void
23prompt (char *label, char *fmt, void *where)
24{
25 printf ("%s: ", label);
26 scanf (fmt, where);
27 while (getchar () != '\n');
28}
29
30int
31log10sz (size_t sz)
32{
33 return ((sz >= 10000000000000000000lu) ? 19 :
34 (sz >= 1000000000000000000lu) ? 18 :
35 (sz >= 100000000000000000lu) ? 17 :
36 (sz >= 10000000000000000lu) ? 16 :
37 (sz >= 1000000000000000lu) ? 15 :
38 (sz >= 100000000000000lu) ? 14 :
39 (sz >= 10000000000000lu) ? 13 :
40 (sz >= 1000000000000lu) ? 12 :
41 (sz >= 100000000000lu) ? 11 :
42 (sz >= 1000000000lu) ? 9 :
43 (sz >= 100000000lu) ? 8 :
44 (sz >= 10000000lu) ? 7 :
45 (sz >= 1000000lu) ? 6 :
46 (sz >= 100000lu) ? 5 :
47 (sz >= 10000lu) ? 4 :
48 (sz >= 1000lu) ? 3 :
49 (sz >= 100lu) ? 2 :
50 (sz >= 10lu) ? 1 : 0u);
51}
52
53gsl_matrix *gsl_matrix_minor (const gsl_matrix *m, size_t row, size_t col) {
54 int n = m->size1 > m->size2 ? m->size1 : m->size2;
55 gsl_matrix *minor = gsl_matrix_alloc (n - 1, n - 1);
56
57 for (size_t i = 0; i < n; ++i) {
58 if (i == row) continue;
59 for (size_t j = 0; j < n; ++j) {
60 if (j == col) continue;
61 gsl_matrix_set (minor,
62 i < row ? i : i - 1,
63 j < col ? j : j - 1,
64 gsl_matrix_get (m, i, j));
65 }
66 }
67
68 return minor;
69}
70
71double
72gsl_matrix_determinant (const gsl_matrix *m)
73{
74 size_t n = m->size1;
75
76 if (n == 1)
77 return gsl_matrix_get (m, 0, 0);
78 if (n == 2) {
79 return
80 gsl_matrix_get (m, 0, 0)*gsl_matrix_get (m, 1, 1) -
81 gsl_matrix_get (m, 0, 1)*gsl_matrix_get (m, 1, 0);
82 }
83
84 double determinant = 0;
85 for (size_t i = 0; i < n; ++i) {
86 gsl_matrix *minor = gsl_matrix_minor (m, 0, i);
87
88 double minor_determinant = gsl_matrix_determinant(minor);
89 gsl_matrix_free (minor);
90
91 determinant += (i % 2 == 0 ? 1 : -1) *
92 gsl_matrix_get (m, 0, i) *
93 minor_determinant;
94 }
95
96 return determinant;
97}
98
99double
100gsl_matrix_cofactor (const gsl_matrix *m, size_t i, size_t j)
101{
102 gsl_matrix *minor = gsl_matrix_minor (m, i, j);
103
104 double minor_determinant = gsl_matrix_determinant (minor);
105
106 return (i + j) % 2 == 0 ? +minor_determinant
107 : -minor_determinant;
108}
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..6883a16
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,33 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <stdlib.h>
5#include <stdbool.h>
6#include <gsl/gsl_spmatrix.h>
7#include <assert.h>
8
9#define MALLOC malloc
10#define REALLOC realloc
11#define FREE free
12#define ASSERT assert
13
14#define MIN(A, B) ({ \
15 A < B ? A : B; \
16})
17
18#define SWAP(A, B) ({ \
19 typeof (A) tmp = (A); \
20 (A) = (B); \
21 (B) = tmp; \
22 })
23
24#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
25
26extern void print_gsl_matrix (const gsl_matrix *);
27extern void prompt (char *label, char *fmt, void *where);
28extern int log10sz (size_t sz);
29
30double gsl_matrix_determinant (const gsl_matrix *);
31double gsl_matrix_cofactor (const gsl_matrix *, size_t i, size_t j);
32
33#endif