~ruther/ctu-fee-eoa

ref: e024536ed1af68510afba8d79775f64cba8acaca ctu-fee-eoa/codes/tsp_hw01/src/union_find.rs -rw-r--r-- 1.1 KiB
e024536e — Rutherther feat: declare problems for hw02 11 days ago
                                                                                
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
#[derive(Clone, Debug, PartialEq)]
pub struct UnionFindElement {
    idx: usize,
    parent: usize,
}

/// A structure for representing components with nodes.
#[derive(Clone, Debug, PartialEq)]
pub struct UnionFind {
    elements: Vec<UnionFindElement>
}

impl UnionFind {
    pub fn make_set(len: usize) -> UnionFind {
        UnionFind {
            elements: (0..len).map(|idx|
                                   UnionFindElement {
                                       idx,
                                       parent: idx
                                   }).collect()
        }
    }

    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Find component of a node.
    pub fn find(&self, x: usize) -> usize {
        let mut current = &self.elements[x];
        while current.parent != current.idx {
            current = &self.elements[current.parent];
        }

        current.idx
    }

    /// Connect two components.
    pub fn union(&mut self, x: usize, y: usize) {
        let x = self.find(x);
        let y = self.find(y);

        self.elements[y].parent = x;
    }
}