-
Notifications
You must be signed in to change notification settings - Fork 6
/
UF.m
46 lines (40 loc) · 1.01 KB
/
UF.m
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
classdef UF
% Weighted-UF algorithm
% stupid implementation
properties
id
sz
count
end
methods
function uf = UF(N)
uf.id = 1:N;
uf.sz = ones(1, N);
uf.count = N;
end
function pid = find_id(uf, p)
while p ~= uf.id(p)
p = uf.id(uf.id(p));
end
pid = p;
end
function ret = connected(uf, p, q)
ret = (find_id(uf, p) == find_id(uf, q));
end
function uf = union(uf, p, q)
i = find_id(uf, p);
j = find_id(uf, q);
if i == j
return
end
if uf.sz(i) < uf.sz(j)
uf.id(i) = j;
uf.sz(j) = uf.sz(j) + uf.sz(i);
else
uf.id(j) = i;
uf.sz(i) = uf.sz(i) + uf.sz(j);
end
uf.count = uf.count - 1;
end
end
end