#include "graph.h" #include "config.h" #include "utils.h" #include "dynamic-array.h" #include #include #include #include #define ALLOC_SQUARE_GSL_MATRIX(n) gsl_matrix_calloc ((n), (n)) gsl_matrix * shimbell_method (GRAPH g, size_t edge_count, bool max) { size_t n = g->vertex_count; gsl_matrix *adj = g->weight_matrix; gsl_matrix *shimbell = ALLOC_SQUARE_GSL_MATRIX (n); gsl_matrix_memcpy (shimbell, adj); if (n == 1) return shimbell; gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX (n); for (size_t l = 0; l < edge_count; ++l) { gsl_matrix_memcpy (tmp, shimbell); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { double bestval = max ? 0 : INFINITY; for (size_t k = 0; k < n; ++k) { double a = gsl_matrix_get (tmp, k, j); double b = gsl_matrix_get (adj, i, k); if (a == 0 || b == 0) continue; double val = a + b; if (max ? val > bestval : val < bestval) { bestval = val; } } gsl_matrix_set (shimbell, i, j, bestval); } } } gsl_matrix_free (tmp); return shimbell; } size_t graph_count_routes (GRAPH g, size_t from, size_t to) { size_t n = g->vertex_count; gsl_matrix *adj = g->adjecency_matrix; gsl_matrix *con = ALLOC_SQUARE_GSL_MATRIX(n); gsl_matrix *pow = ALLOC_SQUARE_GSL_MATRIX(n); gsl_matrix *tmp = ALLOC_SQUARE_GSL_MATRIX(n); for (size_t e = 0; e < n*n; ++e) con->data[e] = adj->data[e] != 0 ? 1 : 0; gsl_matrix_memcpy (pow, con); gsl_matrix_memcpy (tmp, con); size_t count = gsl_matrix_get (pow, from, to); for (size_t k = 0; k < n - 2; ++k) { gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, tmp, con, 0.0, pow); count += gsl_matrix_get (pow, from, to); gsl_matrix *swap = tmp; tmp = pow; pow = swap; } gsl_matrix_free (con); gsl_matrix_free (tmp); gsl_matrix_free (pow); return count; } static inline void is_graph_connected_implementation (gsl_matrix *adj, bool *visited, size_t v) { size_t n = adj->size1; visited[v] = true; for (size_t i = 0; i < n; ++i) { if (!visited[i] && (gsl_matrix_get(adj, v, i) || gsl_matrix_get(adj, i, v))) { is_graph_connected_implementation (adj, visited, i); } } } bool is_graph_connected (GRAPH g) { size_t n = g->vertex_count; bool visited[n]; memset (visited, 0, sizeof (visited)); is_graph_connected_implementation (g->adjecency_matrix, visited, 0); for (size_t i = 0; i < n; ++i) { if (!visited[i]) return false; } return true; } bool is_graph_algebraically_connected (gsl_matrix *adj) { size_t n = adj->size1; gsl_matrix *laplacian = gsl_matrix_alloc (n, n); for (size_t i = 0; i < n; ++i) { double deg = 0; for (size_t j = i + 1; j < n; ++j) { double val = gsl_matrix_get (adj, i, j); gsl_matrix_set (laplacian, j, i, val == 0.0 ? 0.0 : -val); deg += gsl_matrix_get (adj, i, j); } gsl_matrix_set (laplacian, i, i, deg); } gsl_vector *eval = gsl_vector_alloc (n); gsl_eigen_symm_workspace *w = gsl_eigen_symm_alloc (n); gsl_eigen_symm (laplacian, eval, w); gsl_sort_vector (eval); double fiedler = gsl_vector_get (eval, 1); gsl_eigen_symm_free (w); gsl_vector_free (eval); gsl_matrix_free (laplacian); return fiedler > 1e-12 ? true : false; } void generate_graph (GRAPH g, DISTRIBUTION dist, size_t vertex_count, enum graph_type type) { g->vertex_count = vertex_count; g->type = type; size_t n = vertex_count; // size_t m = n - 1; size_t m = MIN (n*3/2, (n*n - n)/2); g -> adjecency_matrix = ALLOC_SQUARE_GSL_MATRIX(n); g -> weight_matrix = ALLOC_SQUARE_GSL_MATRIX(n); g -> capacity_matrix = ALLOC_SQUARE_GSL_MATRIX(n); // for (size_t i = 0; i < n - 1; ++i) { // size_t max_degree = n - i - 1; // size_t degree = floor (distribution_nrand (dist)*(max_degree - 1)) + 1; // for (size_t j = 0; j < degree; ++j) { // double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1; // if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2) // weight = -weight; // double capacity = floor (MAX_CAPACITY*distribution_nrand (dist)); // gsl_matrix_set (g -> adjecency_matrix, i, j + i + 1, 1); // gsl_matrix_set (g -> weight_matrix, i, j + i + 1, weight); // gsl_matrix_set (g -> capacity_matrix, i, j + i + 1, capacity); // } // } for (size_t k = 0; k < m || !is_graph_connected (g); ++k) { size_t r = floor (n*n*distribution_nrand (dist)) + 1; // size_t r = floor (n*n*(rand ()/(double) RAND_MAX)) + 1; ssize_t i = floor ((r - 1)/(double) n); ssize_t j = (r - 1) % n; // printf ("%2zu %zd %zd\n", r, i, j); if (i < j && !gsl_matrix_get (g->adjecency_matrix, i, j)) { double weight = floor ((MAX_WEIGHT - 1)*distribution_nrand (dist)) + 1; if (g->type == GRAPH_TYPE_POSITIVE_NEGATIVE && rand () % 2) weight = -weight; double capacity = floor (MAX_CAPACITY*distribution_nrand (dist)); gsl_matrix_set (g -> adjecency_matrix, i, j, 1); gsl_matrix_set (g -> weight_matrix, i, j, weight); gsl_matrix_set (g -> capacity_matrix, i, j, capacity); } else m += 1; } } size_t * dijkstra_positive (GRAPH g, size_t from, size_t to, bool max) { struct dijkstra_node { double distance; size_t previous; bool visited; }; size_t n = g->vertex_count; double cost[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT]; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { double val = gsl_matrix_get (g->weight_matrix, i, j); if (val == 0) cost[i][j] = max ? -INFINITY : INFINITY; else cost[i][j] = val; } } struct dijkstra_node nodes[MAX_VERTEX_COUNT]; for (size_t i = 0; i < n; ++i) { nodes[i] = (struct dijkstra_node) { .distance = cost[from][i], .previous = from, .visited = false, }; } nodes[from].distance = 0; nodes[from].visited = true; for (size_t count = 1; count < n - 1; ++count) { size_t next; double best_distance = max ? -INFINITY : INFINITY; for (size_t i = 0; i < n; i++) { if ((max ? nodes[i].distance > best_distance : nodes[i].distance < best_distance) && !nodes[i].visited) { best_distance = nodes[i].distance; next = i; } } nodes[next].visited = true; for (size_t i = 0; i < n; ++i) { if (!nodes[i].visited) { double distance = best_distance + cost[next][i]; if ((max ? distance > nodes[i].distance : distance < nodes[i].distance)) { nodes[i].distance = distance; nodes[i].previous = next; } } } } printf ("DISTANCE VECTOR: (%.f", nodes[0].distance); for (size_t i = 0; i < n; ++i) { printf (" %.f", nodes[i].distance); } puts (")"); if (nodes[to].distance == (max ? -INFINITY : INFINITY)) { printf ("NO PATH FROM %zu TO %zu\n", from, to); return NULL; } size_t len = 1; for (size_t i = to; i != from; i = nodes[i].previous) len += 1; size_t *path = malloc ((len + 1)*sizeof (*path)); size_t v = len; path[v--] = n; for (size_t i = to; i != from; i = nodes[i].previous) path[v--] = i; path[v] = from; printf ("PATH: %zu", path[0]); for (size_t i = 1; path[i] != n; ++i) printf (" -> %zu", path[i]); putchar ('\n'); return path; } size_t * floyd_warshall (GRAPH g, size_t from, size_t to, bool max) { const size_t n = g->vertex_count; double dist[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT]; size_t next[MAX_VERTEX_COUNT][MAX_VERTEX_COUNT]; // initialize dist and next for (size_t u = 0; u < n; ++u) { for (size_t v = 0; v < n; ++v) { if (gsl_matrix_get (g->weight_matrix, u, v) == 0) { dist[u][v] = max ? -INFINITY : INFINITY; next[u][v] = n; } else { dist[u][v] = gsl_matrix_get (g->weight_matrix, u, v); next[u][v] = v; } dist[v][v] = 0; next[v][v] = v; } } // compute dist and next for (size_t k = 0; k < n; ++k) { for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { if (max ? dist[i][j] < dist[i][k] + dist[k][j] : dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } puts ("DISTANCE MATRIX:"); printf (" "); for (size_t j = 0; j < n; j++) printf (" [%zu]", j); putchar ('\n'); for (size_t i = 0; i < n; i++) { printf ("[%zu]", i); for (size_t j = 0; j < n; j++) printf ("%4g", dist[i][j]); putchar ('\n'); } // find path if (next[from][to] == n) { printf ("NO PATH FROM %zu TO %zu\n", from, to); return NULL; } size_t len = 1; for (size_t v = from; v != to; v = next[v][to]) len += 1; size_t *path = malloc ((len + 1)*sizeof (*path)); size_t e = 0; for (size_t v = from; v != to; v = next[v][to]) path[e++] = v; path[e++] = to; path[e] = n; printf ("PATH: %zu", path[0]); for (size_t i = 1; path[i] != n; ++i) printf (" -> %zu", path[i]); putchar ('\n'); return path; } void graph_unhighlight (GRAPH g) { free (g->highlighted_path); g->highlighted_path = NULL; DYNAMIC_ARRAY_RESET (g->highlighted_edges); } void graph_edge_set (GRAPH g, size_t from, size_t to, double weight, double capacity) { gsl_matrix_set (g -> adjecency_matrix, from, to, weight && capacity); gsl_matrix_set (g -> weight_matrix, from, to, weight); gsl_matrix_set (g -> capacity_matrix, from, to, capacity); } void print_graph (GRAPH g) { puts ("ADJECENCY_MATRIX:"); print_gsl_matrix (g->adjecency_matrix); puts ("WEIGHT/COST_MATRIX:"); print_gsl_matrix (g->weight_matrix); puts ("CAPACITY_MATRIX:"); print_gsl_matrix (g->capacity_matrix); } bool are_vertices_connected (gsl_matrix *g, size_t from, size_t to) { size_t n = g->size1; struct stack { size_t *items; size_t count; size_t capacity; }; struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n); struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n); struct stack *front_stack = &stack1; struct stack *back_stack = &stack2; DYNAMIC_ARRAY_APPEND (*front_stack, from); while (front_stack->count) { DYNAMIC_ARRAY_RESET (*back_stack); DYNAMIC_ARRAY_FOREACH (v, *front_stack) { size_t vertex = *v; for (size_t i = 0; i < n; ++i) { if (gsl_matrix_get (g, vertex, i)) { if (to == i) return true; DYNAMIC_ARRAY_APPEND (*back_stack, i); } } } SWAP (front_stack, back_stack); } return false; } void highlight_graph (GRAPH g, const gsl_matrix *m) { DYNAMIC_ARRAY_RESET (g->highlighted_edges); size_t n = g->vertex_count; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (m, i, j)) DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {i, j})); } } } // https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm // https://algorithms.discrete.ma.tum.de/graph-algorithms/flow-ford-fulkerson/index_en.html double max_flow_ford_fulkerson (GRAPH g, size_t source, size_t sink) { size_t n = g->vertex_count; size_t parents[MAX_VERTEX_COUNT]; for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i) parents[i] = n; gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n); gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix); double max_flow = 0; struct stack { size_t *items; size_t count; size_t capacity; }; DYNAMIC_ARRAY_RESET (g->highlighted_edges); struct stack stack1 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack1, n); struct stack stack2 = {0}; DYNAMIC_ARRAY_ENSURE_CAPACITY (stack2, n); struct stack *front_stack = &stack1; struct stack *back_stack = &stack2; for (;;) { bool visited[MAX_VERTEX_COUNT] = { false }; DYNAMIC_ARRAY_RESET (*front_stack); DYNAMIC_ARRAY_APPEND (*front_stack, source); visited[source] = true; while (front_stack->count) { DYNAMIC_ARRAY_RESET (*back_stack); DYNAMIC_ARRAY_FOREACH (v, *front_stack) { size_t vertex = *v; for (size_t i = 0; i < n; ++i) { if (!visited[i] && gsl_matrix_get (residual_capacity_matrix, vertex, i) > 0) { parents[i] = vertex; if (sink == i) goto found; DYNAMIC_ARRAY_APPEND (*back_stack, i); visited[i] = true; } } } SWAP(front_stack, back_stack); } break; found: { double path_flow = INFINITY; for (size_t v = sink; v != source; v = parents[v]) { size_t u = parents[v]; DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v})); path_flow = fmin (path_flow, gsl_matrix_get (residual_capacity_matrix, u, v)); } for (size_t v = sink; v != source; v = parents[v]) { size_t u = parents[v]; *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow; *gsl_matrix_ptr (residual_capacity_matrix, v, u) += path_flow; } max_flow += path_flow; } } gsl_matrix_free (residual_capacity_matrix); return max_flow; } // https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG9.pdf double min_cost_flow (GRAPH g, size_t s, size_t t, double required_flow) { size_t n = g->vertex_count; gsl_matrix *residual_capacity_matrix = gsl_matrix_alloc (n, n); gsl_matrix_memcpy (residual_capacity_matrix, g->capacity_matrix); gsl_matrix *residual_cost_matrix = gsl_matrix_alloc (n, n); gsl_matrix_memcpy (residual_cost_matrix, g->weight_matrix); gsl_matrix *result_flow_matrix = gsl_matrix_calloc (n, n); double costs[MAX_VERTEX_COUNT]; size_t parents[MAX_VERTEX_COUNT]; double flow; double min_cost; DYNAMIC_ARRAY_RESET (g->highlighted_edges); while (flow < required_flow) { // Bellman-Ford for (size_t i = 0; i < n; ++i) { costs[i] = INFINITY; parents[i] = n; } costs[s] = 0; for (size_t i = 0; i < n - 1; ++i) { for (size_t u = 0; u < n; ++u) { for (size_t v = 0; v < n; ++v) { if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue; double cost = gsl_matrix_get (residual_cost_matrix, u, v); if (costs[u] != INFINITY && cost != INFINITY && costs[u] + cost < costs[v]) { costs[v] = costs[u] + cost; parents[v] = u; } } } } // If no path if (parents[t] == n) return NAN; // Find max flow double path_flow = INFINITY; for (size_t v = t; v != s; v = parents[v]) { size_t u = parents[v]; path_flow = fmin (path_flow, gsl_matrix_get (residual_capacity_matrix, u, v)); } // Apply flow constraint path_flow = fmin (path_flow, required_flow - flow); // Update costs and capacities for (int v = t; v != s; v = parents[v]) { int u = parents[v]; DYNAMIC_ARRAY_APPEND (g->highlighted_edges, ((struct edge) {u, v})); *gsl_matrix_ptr (residual_capacity_matrix, u, v) -= path_flow; *gsl_matrix_ptr (result_flow_matrix, u, v) += path_flow; min_cost += path_flow*gsl_matrix_get (residual_cost_matrix, u, v); if (gsl_matrix_get (residual_capacity_matrix, u, v) == 0) gsl_matrix_set (residual_cost_matrix, u, v, INFINITY); } flow += path_flow; } puts ("FLOW_MATRIX:"); print_gsl_matrix (result_flow_matrix); gsl_matrix_free (residual_capacity_matrix); gsl_matrix_free (residual_cost_matrix); gsl_matrix_free (result_flow_matrix); return min_cost; } size_t count_spanning_trees (GRAPH g) { size_t n = g->vertex_count; gsl_matrix *kirchhoff_matrix = gsl_matrix_calloc (n, n); for (size_t i = 0; i < n; i++) { for (size_t j = i; j < n; j++) { if (gsl_matrix_get (g->adjecency_matrix, i, j) || gsl_matrix_get (g->adjecency_matrix, j, i)) { *gsl_matrix_ptr (kirchhoff_matrix, i, i) += 1; *gsl_matrix_ptr (kirchhoff_matrix, j, j) += 1; *gsl_matrix_ptr (kirchhoff_matrix, i, j) = -1; *gsl_matrix_ptr (kirchhoff_matrix, j, i) = -1; } } } printf ("KIRCHHOFF_MATRIX:\n"); print_gsl_matrix (kirchhoff_matrix); size_t count = gsl_matrix_cofactor (kirchhoff_matrix, 0, 0); gsl_matrix_free (kirchhoff_matrix); return count; } // https://en.wikipedia.org/wiki/Prim%27s_algorithm gsl_matrix * min_weight_spannig_tree_prim (GRAPH g) { size_t count = 0; double total_weight = 0; size_t n = g->vertex_count; gsl_matrix *remaining_graph = gsl_matrix_alloc (n, n); for (size_t i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { double weight = gsl_matrix_get (g->weight_matrix, i, j); gsl_matrix_set (remaining_graph, i, j, weight == 0 ? INFINITY : weight); } } gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n); bool visited[MAX_VERTEX_COUNT] = {0}; size_t spanning_tree_vertex_count = 0; while (spanning_tree_vertex_count < g->vertex_count) { double minimum_weight = INFINITY; size_t a; size_t b; for (size_t i = 0 ; i < n; ++i) { for (size_t j = 0; j < n; ++j) { count += 1; double weight = gsl_matrix_get (remaining_graph, i, j); if (weight < minimum_weight && ((visited[i] != visited[j]) || spanning_tree_vertex_count == 0)) { minimum_weight = weight; a = i; b = j; } } } if (!visited[a] || !visited[b]) { if (!visited[a]) { spanning_tree_vertex_count += 1; visited[a] = true; } if (!visited[b]) { spanning_tree_vertex_count += 1; visited[b] = true; } total_weight += minimum_weight; } gsl_matrix_set (remaining_graph, a, b, INFINITY); gsl_matrix_set (remaining_graph, b, a, INFINITY); gsl_matrix_set (spanning_tree, a, b, minimum_weight); gsl_matrix_set (spanning_tree, b, a, minimum_weight); printf ("%zu %zu = %f\n", a, b, minimum_weight); } gsl_matrix_free (remaining_graph); printf ("MINIMUM_SPANNING_TREE_WEIGHTS:\n"); print_gsl_matrix (spanning_tree); printf ("TOTAL_WEIGHT: %.0lf\n", total_weight); printf ("ITERATION_COUNT: %zu\n", count); return spanning_tree; } // https://en.wikipedia.org/wiki/Bor%C5%AFvka's_algorithm gsl_matrix * min_weight_spannig_tree_boruvka (GRAPH g) { size_t n = g->vertex_count; gsl_matrix *spanning_tree = gsl_matrix_calloc (n, n); struct edge_weight { size_t from; size_t to; double weight; }; size_t number_of_components = g->vertex_count; struct edge_weight lightest_edges[MAX_VERTEX_COUNT]; size_t parent_components[MAX_VERTEX_COUNT]; size_t next_components[MAX_VERTEX_COUNT]; for (size_t i = 0; i < n; ++i) parent_components[i] = i; size_t count = 0; double min_weight = 0; while (number_of_components > 1) { for (size_t i = 0; i < n; ++i) lightest_edges[i] = (struct edge_weight) { 0, 0, .weight = INFINITY }; for (size_t u = 0; u < n; ++u) { for (size_t v = 0; v < n; ++v) { if (!gsl_matrix_get (g->adjecency_matrix, u, v)) continue; count += 1; double weight = gsl_matrix_get (g->weight_matrix, u, v) + gsl_matrix_get (g->weight_matrix, v, u); if (parent_components[u] != parent_components[v]) { if (lightest_edges[parent_components[u]].weight > weight) { lightest_edges[parent_components[u]].weight = weight; lightest_edges[parent_components[u]].from = u; lightest_edges[parent_components[u]].to = v; } if (lightest_edges[parent_components[v]].weight > weight) { lightest_edges[parent_components[v]].weight = weight; lightest_edges[parent_components[v]].from = u; lightest_edges[parent_components[v]].to = v; } } } } // Adding selected edges and combining components for (size_t i = 0; i < number_of_components; ++i) { count++; double weight = lightest_edges[i].weight; size_t u = lightest_edges[i].from; size_t v = lightest_edges[i].to; if (weight == INFINITY) continue; if (!gsl_matrix_get (spanning_tree, u, v)) { min_weight += weight; gsl_matrix_set (spanning_tree, u, v, weight); gsl_matrix_set (spanning_tree, v, u, weight); } // Do the join if (parent_components[u] != parent_components[v]) { number_of_components -= 1; size_t component_to_remove = parent_components[v]; for (size_t j = 0; j < n; j++) { if (parent_components[j] == component_to_remove) { parent_components[j] = parent_components[u]; } } } } } printf ("MINIMUM_SPANNING_TREE_WEIGHTS:\n"); print_gsl_matrix (spanning_tree); printf ("TOTAL_WEIGHT: %.0lf\n", min_weight); printf ("ITERATION_COUNT: %zu\n", count); return spanning_tree; } void prufer_code (gsl_matrix *spanning_tree_matrix) { size_t n = spanning_tree_matrix->size1; gsl_matrix *tree = gsl_matrix_alloc (n, n); gsl_matrix_memcpy (tree, spanning_tree_matrix); struct { size_t *items; size_t count; size_t capacity; } prufer = {0}; struct { size_t *items; size_t count; size_t capacity; } weights = {0}; for (size_t i = 0; i < n - 1; ++i) { // Find hanging vertex with the lowest number size_t v, u; for (size_t j = 0; j < n; ++j) { size_t deg = 0; for (size_t k = 0; k < n; ++k) { if (gsl_matrix_get (tree, j, k) > 0) { deg += 1; u = k; } } if (deg == 1) { v = j; break; } } // Encode the only vertex neighbouring `v' DYNAMIC_ARRAY_APPEND (prufer, u); DYNAMIC_ARRAY_APPEND (weights, gsl_matrix_get (tree, u, v)); // "Pop" gsl_matrix_set (tree, u, v, 0); gsl_matrix_set (tree, v, u, 0); } printf ("MINIMAL_SPANNING_TREE:\n"); print_gsl_matrix (spanning_tree_matrix); printf ("PRUFER_CODE: "); DYNAMIC_ARRAY_FOREACH (p, prufer) printf ("%zu ", *p); printf ("\n"); printf ("SAVED_WEIGHTS: "); DYNAMIC_ARRAY_FOREACH (w, weights) printf ("%zu ", *w); printf ("\n"); // Decoding gsl_matrix *decoded_tree = gsl_matrix_calloc (n, n); struct { size_t *items; size_t count; size_t capacity; } not_used_vertices = {0}; for (size_t i = 0; i < n; ++i) DYNAMIC_ARRAY_APPEND (not_used_vertices, i); for (size_t i = 0; i < n - 1; ++i) { // Picking unused vertex v with the lowest number not in the rest // of the Prufer code size_t v; for (size_t j = 0; j < not_used_vertices.count; ++j) { bool met = false; for (size_t k = i; k < n - 1; ++k) { if (not_used_vertices.items[j] == prufer.items[k]) { met = true; break; } } if (!met) { v = not_used_vertices.items[j]; // Remove now used DYNAMIC_ARRAY_ERASE (not_used_vertices, j); break; } } // Add edge gsl_matrix_set (decoded_tree, v, prufer.items[i], weights.items[i]); gsl_matrix_set (decoded_tree, prufer.items[i], v, weights.items[i]); } printf ("DECODED_MINIMAL_SPANNING_TREE:\n"); print_gsl_matrix (decoded_tree); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (spanning_tree_matrix, i, j) != gsl_matrix_get (decoded_tree, i, j)) { printf ("Error, matrices are not the same!\n"); return; } } } printf("Success, matrices the same!\n"); gsl_matrix_free (tree); gsl_matrix_free (decoded_tree); } bool is_graph_eulerian (GRAPH g) { size_t n = g->vertex_count; if (n <= 2) return false; // Check if degree of all vertices is even for (size_t i = 0; i < n; ++i) { size_t degree = 0; for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (g->adjecency_matrix, i, j) || gsl_matrix_get (g->adjecency_matrix, j, i)) degree += 1; } if (degree % 2 != 0) return false; } return true; } // https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG12.pdf // page 33 bool is_graph_hamiltonian (GRAPH g) { size_t n = g->vertex_count; // Find neighbours struct { size_t *items; size_t count; size_t capacity; } neighbours[MAX_VERTEX_COUNT] = {0}; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (g->adjecency_matrix, i, j) || gsl_matrix_get (g->adjecency_matrix, j, i)) { DYNAMIC_ARRAY_APPEND (neighbours[i], j); } } } struct { size_t *items; size_t count; size_t capacity; } not_visited_neighbours[MAX_VERTEX_COUNT] = {0}; struct { size_t *items; size_t count; size_t capacity; } path = {0}; size_t a = 0; DYNAMIC_ARRAY_APPEND (path, a); DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[a], neighbours[a]); while (path.count) { size_t x = path.items[path.count - 1]; if (not_visited_neighbours[x].count) { size_t y = not_visited_neighbours[x].items[not_visited_neighbours[x].count - 1]; not_visited_neighbours[x].count -= 1; bool y_in_path = false; DYNAMIC_ARRAY_FOREACH(p, path) { if (*p == y) { y_in_path = true; break; } } if (!y_in_path) { DYNAMIC_ARRAY_APPEND (path, y); DYNAMIC_ARRAY_COPY_OTHER (not_visited_neighbours[y], neighbours[y]); if (path.count == n && (gsl_matrix_get (g->adjecency_matrix, a, y) || gsl_matrix_get (g->adjecency_matrix, y, a))) { return true; } } } else { path.count -= 1; // pop back } } return false; } void graph_ensure_eulerian (GRAPH g) { size_t n = g->vertex_count; if (n <= 2) { printf ("Not enough vertices for an Euler cycle (<3)\n"); return; } if (is_graph_eulerian (g)) { printf ("Graph is Eulerian, no modifications needed\n"); } else { // Find vertices with odd degrees struct { size_t *items; size_t count; size_t capacity; } odd_degree_vertices = {0}; for (size_t i = 0; i < n; ++i) { size_t degree = 0; for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (g->adjecency_matrix, i, j) || gsl_matrix_get (g->adjecency_matrix, j, i)) degree += 1; } if (degree % 2 != 0) DYNAMIC_ARRAY_APPEND (odd_degree_vertices, i); } size_t first; // Join vertices with odd degrees add_edge: if (odd_degree_vertices.count) first = odd_degree_vertices.items[0]; // Find pair for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) { size_t second = odd_degree_vertices.items[second_index]; // Help keep acyclic size_t i = first < second ? first : second; size_t j = first > second ? first : second; // Add edge if there isn't if (gsl_matrix_get (g->adjecency_matrix, i, j) == 0 && gsl_matrix_get (g->adjecency_matrix, j, i) == 0) { double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1; double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1; graph_edge_set (g, i, j, new_weight, new_capacity); printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight); // Update DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index); DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0); goto add_edge; } } // If edge addition helped only partially, delete edges remove_edge: if (odd_degree_vertices.count) first = odd_degree_vertices.items[0]; for (size_t second_index = 1; second_index < odd_degree_vertices.count; ++second_index) { size_t second = odd_degree_vertices.items[second_index]; size_t i = first < second ? first : second; size_t j = first > second ? first : second; // Don't delete edge if it will make graph unconnected size_t degree_i = 0; size_t degree_j = 0; for (size_t k = 0; k < n; ++k) { if (gsl_matrix_get (g->adjecency_matrix, i, k) || gsl_matrix_get (g->adjecency_matrix, k, i)) degree_i += 1; if (gsl_matrix_get (g->adjecency_matrix, j, k) || gsl_matrix_get (g->adjecency_matrix, k, j)) degree_j += 1; } if (degree_i == 1 && degree_j == 1) continue; gsl_matrix_set (g -> adjecency_matrix, i, j, 0); gsl_matrix_set (g -> weight_matrix, i, j, 0); gsl_matrix_set (g -> capacity_matrix, i, j, 0); gsl_matrix_set (g -> adjecency_matrix, j, i, 0); gsl_matrix_set (g -> weight_matrix, j, i, 0); gsl_matrix_set (g -> capacity_matrix, j, i, 0); printf ("Removed edge: %zu -> %zu\n", i, j); // Update DYNAMIC_ARRAY_ERASE (odd_degree_vertices, second_index); DYNAMIC_ARRAY_ERASE (odd_degree_vertices, 0); goto remove_edge; } if (odd_degree_vertices.count) printf ("Unable to make graph Eulerian\n"); printf ("ADJECENCY_MATRIX:\n"); print_gsl_matrix (g->adjecency_matrix); } // Find Euler cycles // Find neighbours struct { size_t *items; size_t count; size_t capacity; } neighbours[MAX_VERTEX_COUNT] = {0}; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (g->adjecency_matrix, i, j) || gsl_matrix_get (g->adjecency_matrix, j, i)) { DYNAMIC_ARRAY_APPEND (neighbours[i], j); } } } // https://tema.spbstu.ru/userfiles/files/courses/2019-theory_graph/TG12.pdf // Page 27 struct { size_t *items; size_t count; size_t capacity; } euler_cycle = {0}; struct { size_t *items; size_t count; size_t capacity; } s = {0}; DYNAMIC_ARRAY_APPEND (s, 0); while (s.count) { size_t v = s.items[s.count - 1]; if (!neighbours[v].count) { s.count -= 1; DYNAMIC_ARRAY_APPEND (euler_cycle, v); } else { size_t u = neighbours[v].items[0]; DYNAMIC_ARRAY_APPEND (s, u); // Removing DYNAMIC_ARRAY_ERASE (neighbours[v], 0); for (size_t i = 0; i < neighbours[u].count; ++i) { if (neighbours[u].items[i] == v) { DYNAMIC_ARRAY_ERASE (neighbours[u], i); i -= 1; } } } } printf ("EULER_CYCLE: "); DYNAMIC_ARRAY_FOREACH (vertex, euler_cycle) { if (vertex != euler_cycle.items) printf (" -> "); printf ("%zu", *vertex); } printf ("\n"); DYNAMIC_ARRAY_APPEND (euler_cycle, n); free (g->highlighted_path); g->highlighted_path = euler_cycle.items; for (size_t i = 0; i < MAX_VERTEX_COUNT; ++i) DYNAMIC_ARRAY_FREE (neighbours[i]); DYNAMIC_ARRAY_FREE (s); // DYNAMIC_ARRAY_FREE (euler_cycle); } void graph_ensure_hamiltonian (GRAPH g) { size_t n = g->vertex_count; if (n <= 2) { printf ("Not enough vertices for an Hamilton cycle (<3)\n"); return; } if (is_graph_hamiltonian (g)) { printf ("Graph is Hamiltonian, no modifications needed\n"); } else { struct { struct vertex_degree { size_t vertex; size_t degree; } *items; size_t count; size_t capacity; } vertex_degree_pairs = {0}; for (size_t i = 0; i < n; ++i) { size_t degree = 0; for (size_t j = 0; j < n; ++j) { if (gsl_matrix_get (g->adjecency_matrix, i, j) || gsl_matrix_get (g->adjecency_matrix, j, i)) degree += 1; } DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {i, degree})); } // Add edges to vertices with low degree do { size_t min_idx = 0; for (size_t i = 1; i < n; ++i) { if (vertex_degree_pairs.items[i].degree < vertex_degree_pairs.items[min_idx].degree) min_idx = i; } size_t vertex1 = vertex_degree_pairs.items[min_idx].vertex; size_t degree1 = vertex_degree_pairs.items[min_idx].degree; DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx); for (size_t k = 0; k < n; ++k) { size_t min_idx = 0; for (size_t i = 1; i < n; ++i) { if (vertex_degree_pairs.items[min_idx].vertex != vertex1 && vertex_degree_pairs.items[i].degree < vertex_degree_pairs.items[min_idx].degree) min_idx = i; } size_t vertex2 = vertex_degree_pairs.items[min_idx].vertex; size_t degree2 = vertex_degree_pairs.items[min_idx].degree; if (!gsl_matrix_get (g->adjecency_matrix, vertex1, vertex2) && !gsl_matrix_get (g->adjecency_matrix, vertex2, vertex1)) { size_t i = vertex1 < vertex2 ? vertex1 : vertex2; size_t j = vertex1 > vertex2 ? vertex1 : vertex2; double new_weight = floor (rand ()/(double) RAND_MAX*(MAX_WEIGHT - 1)) + 1; double new_capacity = floor (rand ()/(double) RAND_MAX*(MAX_CAPACITY - 1)) + 1; graph_edge_set (g, i, j, new_weight, new_capacity); printf ("Added edge: %zu -> %zu (%.0lf/%.0lf)\n", i, j, new_capacity, new_weight); DYNAMIC_ARRAY_ERASE (vertex_degree_pairs, min_idx); DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex2, degree2 + 1})); break; } } DYNAMIC_ARRAY_APPEND (vertex_degree_pairs, ((struct vertex_degree) {vertex1, degree1 + 1})); } while (!is_graph_hamiltonian(g)); } find_hamiltonian_cycles (g); } struct path { size_t *items; size_t count; size_t capacity; } typedef *PATH; void find_hamiltonian_recursive (GRAPH g, FILE *fd, size_t *cycle_count, size_t start, PATH path, double path_weight, PATH min_path, double *min_path_weight) { if (*cycle_count >= 1000000) return; // Path is built if (path->count == g->vertex_count) { size_t last = path->items[path->count - 1]; if (gsl_matrix_get (g->adjecency_matrix, last, start) || gsl_matrix_get (g->adjecency_matrix, start, last)) { *cycle_count += 1; path_weight += gsl_matrix_get (g->weight_matrix, start, last) + gsl_matrix_get (g->weight_matrix, last, start); DYNAMIC_ARRAY_APPEND (*path, start); if (*min_path_weight > path_weight) { DYNAMIC_ARRAY_COPY_OTHER (*min_path, *path); *min_path_weight = path_weight; } for (size_t i = 0; i < path->count; ++i) fprintf (fd, "%zu ", path->items[i]); fprintf (fd, "@ %.0lf\n", path_weight); path->count -= 1; } return; } // Continue building for (size_t i = 0; i < g->vertex_count; ++i) { size_t last = path->items[path->count - 1]; if (!gsl_matrix_get (g->adjecency_matrix, last, i) && !gsl_matrix_get (g->adjecency_matrix, i, last)) continue; bool used = false; DYNAMIC_ARRAY_FOREACH (v, *path) { if (*v == i) { used = true; break; } } if (used) continue; double new_weight = path_weight + gsl_matrix_get (g->weight_matrix, last, i) + gsl_matrix_get (g->weight_matrix, i, last); DYNAMIC_ARRAY_APPEND (*path, i); find_hamiltonian_recursive (g, fd, cycle_count, start, path, new_weight, min_path, min_path_weight); path->count -= 1; } } void find_hamiltonian_cycles (GRAPH g) { const char *filename = "hamiltonian-cycles.txt"; if (g->vertex_count > 20) { printf ("Graph is too large (>20v), iterative algorithm will take too long\n"); return; } FILE *fd = fopen (filename, "w+"); struct path path = {0}; struct path min_path = {0}; size_t cycle_count = 0; double min_path_weight = INFINITY; for (size_t i = 0; i < g->vertex_count; ++i) { DYNAMIC_ARRAY_RESET (path); DYNAMIC_ARRAY_APPEND (path, i); find_hamiltonian_recursive (g, fd, &cycle_count, i, &path, 0, &min_path, &min_path_weight); } fclose (fd); printf ("CYCLES_TOTAL: %zu\n", cycle_count); printf ("All cycles are saved here: %s\n", filename); printf ("Cycle with minimum weight (%.0lf): ", min_path_weight); DYNAMIC_ARRAY_FOREACH (vertex, min_path) { if (vertex != min_path.items) printf (" -> "); printf ("%zu", *vertex); } printf ("\n"); DYNAMIC_ARRAY_APPEND (min_path, g->vertex_count); free (g->highlighted_path); g->highlighted_path = min_path.items; DYNAMIC_ARRAY_FREE (path); }