1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/// Represents an undirected, weighted edge in a graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Edge {
pub src: usize,
pub dst: usize,
pub weight: i32,
}
/// Disjoint-set (union-find) for cycle detection in Kruskal's algorithm.
pub struct UnionFind {
parent: Vec<usize>,
#[allow(dead_code)]
rank: Vec<usize>,
}
impl UnionFind {
/// Initializes a union-find for `n` elements (0..n-1).
pub fn new(n: usize) -> Self {
Self {
parent: (0..n).collect(),
rank: vec![0; n],
}
}
/// Finds the representative (root) of the set containing `x`.
/// Uses path compression.
pub fn find(&mut self, x: usize) -> usize {
if self.parent[x] != x {
self.parent[x] = self.find(self.parent[x]);
}
self.parent[x]
}
/// Unites the sets containing `x` and `y`.
/// Returns `true` if a union actually occurred (i.e., they were disjoint).
pub fn union(&mut self, x: usize, y: usize) -> bool {
let rx = self.find(x);
let ry = self.find(y);
if rx != ry {
// Always make the lower-numbered vertex the root
if rx < ry {
self.parent[ry] = rx;
} else {
self.parent[rx] = ry;
}
true
} else {
false
}
}
}
/// Kruskal's algorithm to compute the MST for an undirected, weighted graph.
///
/// - `num_nodes` is the number of vertices in the graph (assumed labeled 0..(num_nodes-1)).
/// - `edges` is a mutable slice of [`Edge`].
///
/// Returns the edges that form the MST.
/// If the graph is disconnected, this will return a spanning forest of all connected components.
pub fn kruskal(num_nodes: usize, edges: &mut [Edge]) -> Vec<Edge> {
// Sort edges by weight
edges.sort_by_key(|e| e.weight);
println!("\nInitial edges:");
for e in edges.iter() {
println!(" ({}, {}) = {}", e.src, e.dst, e.weight);
}
let mut uf = UnionFind::new(num_nodes);
let mut mst = Vec::with_capacity(num_nodes.saturating_sub(1));
for edge in edges.iter() {
if uf.find(edge.src) != uf.find(edge.dst) {
println!(
"\nAdding edge ({}, {}) = {}",
edge.src, edge.dst, edge.weight
);
println!(
" Before union: {} and {} in different components",
edge.src, edge.dst
);
mst.push(edge.clone());
uf.union(edge.src, edge.dst);
println!(
" After union: {} and {} now in same component",
edge.src, edge.dst
);
println!(
" Current MST weight: {}",
mst.iter().map(|e| e.weight).sum::<i32>()
);
if mst.len() == num_nodes.saturating_sub(1) {
break;
}
} else {
println!(
"\nSkipping edge ({}, {}) = {}",
edge.src, edge.dst, edge.weight
);
println!(" Already in same component (root {})", uf.find(edge.src));
}
}
println!("\nFinal MST:");
for e in mst.iter() {
println!(" ({}, {}) = {}", e.src, e.dst, e.weight);
}
println!(
"Total weight: {}",
mst.iter().map(|e| e.weight).sum::<i32>()
);
mst
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_graph() {
let mut edges = vec![];
let mst = kruskal(0, &mut edges);
assert!(mst.is_empty(), "MST of empty graph should be empty");
}
#[test]
fn test_single_vertex_no_edges() {
let mut edges = vec![];
let mst = kruskal(1, &mut edges);
assert!(
mst.is_empty(),
"MST of single vertex with no edges should be empty"
);
}
#[test]
fn test_single_edge() {
let mut edges = vec![Edge {
src: 0,
dst: 1,
weight: 2,
}];
let mst = kruskal(2, &mut edges);
assert_eq!(mst.len(), 1);
assert_eq!(
mst[0],
Edge {
src: 0,
dst: 1,
weight: 2
}
);
}
#[test]
fn test_disconnected_components() {
let mut edges = vec![
Edge {
src: 0,
dst: 1,
weight: 1,
},
Edge {
src: 2,
dst: 3,
weight: 2,
},
];
// 4 nodes: (0,1) is disconnected from (2,3)
let mst = kruskal(4, &mut edges);
assert_eq!(
mst.len(),
2,
"Should return one edge per connected component minus 1 edge each."
);
// Check that each edge is in the MST
assert!(mst.contains(&Edge {
src: 0,
dst: 1,
weight: 1
}));
assert!(mst.contains(&Edge {
src: 2,
dst: 3,
weight: 2
}));
}
#[test]
fn test_standard_graph() {
// A small graph with 4 vertices
// (0)---10---(1)
// | \ /
// 6 5 15
// | \ /
// (2)---4---(3)
let mut edges = vec![
Edge {
src: 0,
dst: 1,
weight: 10,
},
Edge {
src: 0,
dst: 2,
weight: 6,
},
Edge {
src: 0,
dst: 3,
weight: 5,
},
Edge {
src: 1,
dst: 3,
weight: 15,
},
Edge {
src: 2,
dst: 3,
weight: 4,
},
];
let mst = kruskal(4, &mut edges);
// MST should be edges: (2-3=4), (0-3=5), (0-1=10)
assert_eq!(mst.len(), 3);
// Check minimal total weight:
let total_weight: i32 = mst.iter().map(|e| e.weight).sum();
// The MST must include:
// 1. (2-3) = 4 (lowest weight edge)
// 2. (0-3) = 5 (next lowest, connects 0)
// 3. (0-1) = 10 (connects last vertex 1)
// Total = 4 + 5 + 10 = 19
assert_eq!(
total_weight, 19,
"Kruskal's MST should have a total weight of 19"
);
// Verify specific edges
assert!(mst.contains(&Edge {
src: 2,
dst: 3,
weight: 4
}));
assert!(mst.contains(&Edge {
src: 0,
dst: 3,
weight: 5
}));
assert!(mst.contains(&Edge {
src: 0,
dst: 1,
weight: 10
}));
}
#[test]
fn test_negative_weights() {
let mut edges = vec![
Edge {
src: 0,
dst: 1,
weight: -2,
},
Edge {
src: 1,
dst: 2,
weight: -3,
},
Edge {
src: 0,
dst: 2,
weight: -1,
},
Edge {
src: 2,
dst: 3,
weight: 2,
},
];
let mst = kruskal(4, &mut edges);
// MST for 4 vertices will have 3 edges.
assert_eq!(mst.len(), 3);
let total_weight: i32 = mst.iter().map(|e| e.weight).sum();
// The smallest edges by weight are -3, -2, -1 => but we can only pick 2 or 3 of them
// depending on whether they form a cycle. Actually, -3 (1-2), -2 (0-1), and 2 (2-3)
// or -3, -1, 2 or -2, -1, 2. Let's see:
// sort: (-3 -> 1-2), (-2 -> 0-1), (-1 -> 0-2), (2 -> 2-3)
// picks: (-3 -> 1-2), (-2 -> 0-1) => next is (-1 -> 0-2) but that forms a cycle (0,1,2).
// so it picks (2 -> 2-3). total = -3 + -2 + 2 = -3.
assert_eq!(
total_weight, -3,
"MST should properly handle negative weights"
);
}
#[test]
fn test_parallel_edges() {
// Graph with parallel edges between the same vertices
let mut edges = vec![
Edge {
src: 0,
dst: 1,
weight: 10,
},
Edge {
src: 0,
dst: 1,
weight: 1,
}, // parallel edge, smaller weight
Edge {
src: 1,
dst: 2,
weight: 5,
},
];
// 3 vertices (0,1,2). MST should pick the edge with weight 1, not 10
let mst = kruskal(3, &mut edges);
assert_eq!(mst.len(), 2);
// Check that the smaller parallel edge was chosen
assert!(mst.contains(&Edge {
src: 0,
dst: 1,
weight: 1
}));
// The other edge to connect all nodes is (1-2)
assert!(mst.contains(&Edge {
src: 1,
dst: 2,
weight: 5
}));
}
}