link_cut_tree.rs 10.4 KB
Newer Older
tgerstel's avatar
tgerstel committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use super::collections::{Label, Pool};

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Node<V> {
    value: V,
    path_parent: Option<Label<Node<V>>>,
    parent: Option<Label<Node<V>>>,
    left: Option<Label<Node<V>>>,
    right: Option<Label<Node<V>>>,
}

impl<V> Node<V> {
    pub fn new(value: V) -> Self {
        Node {
            value,
            path_parent: None,
            parent: None,
            left: None,
            right: None,
        }
    }
}

impl<V> Pool<Node<V>> {
tgerstel's avatar
tgerstel committed
25
26
27
28
29
    pub fn add_node(&mut self, value: V) -> Label<Node<V>> {
        let node = Node::new(value);
        self.insert(node)
    }

tgerstel's avatar
tgerstel committed
30
31
    pub fn find_root(&mut self, label: Label<Node<V>>) -> Label<Node<V>> {
        self.expose(label);
tgerstel's avatar
tgerstel committed
32
33
34
35
        let mut root = label;
        while let Some(next) = self.left(root) {
            root = next;
        }
tgerstel's avatar
tgerstel committed
36
37
38
39
40
41
        self.expose(root);
        root
    }

    pub fn cut(&mut self, label: Label<Node<V>>) {
        self.expose(label);
tgerstel's avatar
tgerstel committed
42
43
44
45
        if let Some(left_label) = self.left(label) {
            self[left_label].parent = None;
            self[label].left = None;
        }
tgerstel's avatar
tgerstel committed
46
47
48
49
50
    }

    pub fn link(&mut self, parent_label: Label<Node<V>>, child_label: Label<Node<V>>) {
        self.expose(child_label);
        self.expose(parent_label);
tgerstel's avatar
tgerstel committed
51
52
        self[child_label].left = parent_label.into();
        self[parent_label].parent = child_label.into();
tgerstel's avatar
tgerstel committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    }

    pub fn value_mut(&mut self, label: Label<Node<V>>) -> &mut V {
        &mut self[label].value
    }

    pub fn value(&self, label: Label<Node<V>>) -> &V {
        &self[label].value
    }

    fn expose(&mut self, label: Label<Node<V>>) {
        self.splay(label);
        self.split_right_and_attach_new(label, None);
        let mut v = label;
        while let Some(w) = self[v].path_parent {
            self.splay(w);
            self.split_right_and_attach_new(w, v.into());
            v = w;
        }
        self.splay(label);
    }

tgerstel's avatar
tgerstel committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    fn splay(&mut self, label: Label<Node<V>>) {
        while let Some(parent_label) = self[label].parent {
            if self[parent_label].parent.is_some() {
                if self.is_left_child(label) == self.is_left_child(parent_label) {
                    self.rotate_up(self[label].parent.unwrap());
                    self.rotate_up(label);
                } else {
                    self.rotate_up(label);
                    self.rotate_up(label);
                };
            } else {
                self.rotate_up(label);
                break;
            }
tgerstel's avatar
tgerstel committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
        }
    }

    fn is_left_child(&self, label: Label<Node<V>>) -> bool {
        if let Some(self_label) = self[label]
            .parent
            .map(|parent_label| self[parent_label].left)
            .flatten()
        {
            self_label == label
        } else {
            false
        }
    }

tgerstel's avatar
tgerstel committed
104
105
106
107
    fn rotate_up(&mut self, label: Label<Node<V>>) {
        if let Some(parent_label) = self[label].parent {
            if self.is_left_child(label) {
                self.rotate_right(parent_label);
tgerstel's avatar
tgerstel committed
108
            } else {
tgerstel's avatar
tgerstel committed
109
                self.rotate_left(parent_label);
tgerstel's avatar
tgerstel committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
            }
        }
    }

    fn rotate_right(&mut self, root_label: Label<Node<V>>) {
        if let Some(new_root_label) = self[root_label].left {
            self.set_left(root_label, self[new_root_label].right);
            self.update_parent(root_label, new_root_label);
            self.set_right(new_root_label, Some(root_label));
        }
    }

    fn rotate_left(&mut self, root_label: Label<Node<V>>) {
        if let Some(new_root_label) = self[root_label].right {
            self.set_right(root_label, self[new_root_label].left);
            self.update_parent(root_label, new_root_label);
            self.set_left(new_root_label, Some(root_label));
        }
    }

tgerstel's avatar
tgerstel committed
130
131
132
133
    fn update_parent(&mut self, old_root_label: Label<Node<V>>, new_root_label: Label<Node<V>>) {
        if let Some(parent_label) = self[old_root_label].parent {
            if self.is_left_child(old_root_label) {
                self.set_left(parent_label, Some(new_root_label))
tgerstel's avatar
tgerstel committed
134
            } else {
tgerstel's avatar
tgerstel committed
135
                self.set_right(parent_label, Some(new_root_label));
tgerstel's avatar
tgerstel committed
136
            }
tgerstel's avatar
tgerstel committed
137
138
139
140
141
        } else {
            self[new_root_label].parent = None;
            // Only need to update path parent if original was the root, as only the root has the path_parent
            self[new_root_label].path_parent = self[old_root_label].path_parent;
            self[old_root_label].path_parent = None;
tgerstel's avatar
tgerstel committed
142
143
144
        }
    }

tgerstel's avatar
tgerstel committed
145
146
147
148
149
150
151
152
    fn left(&self, label: Label<Node<V>>) -> Option<Label<Node<V>>> {
        self[label].left
    }

    fn right(&self, label: Label<Node<V>>) -> Option<Label<Node<V>>> {
        self[label].right
    }

tgerstel's avatar
tgerstel committed
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
    fn set_right(&mut self, parent_label: Label<Node<V>>, right_label: Option<Label<Node<V>>>) {
        self[parent_label].right = right_label;
        if let Some(label) = right_label {
            self[label].parent = Some(parent_label);
        }
    }

    fn set_left(&mut self, parent_label: Label<Node<V>>, left_label: Option<Label<Node<V>>>) {
        self[parent_label].left = left_label;
        if let Some(label) = left_label {
            self[label].parent = Some(parent_label);
        }
    }

    fn split_right_and_attach_new(
        &mut self,
        label: Label<Node<V>>,
        new_right: Option<Label<Node<V>>>,
    ) {
        if let Some(right_label) = self.right(label) {
            self[right_label].path_parent = label.into();
            self[right_label].parent = None;
        }

        self[label].right = new_right;
        if let Some(new_right_label) = new_right {
            self[new_right_label].parent = label.into();
            self[new_right_label].path_parent = None;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut lct = Pool::<Node<&str>>::with_capacity(3);

        let node1 = lct.add_node("alpha");
        lct.rotate_down(node1);
        let node2 = lct.add_node("bravo");
        let node3 = lct.add_node("charlie");
        lct.set_left(node1, Some(node2));
        lct.set_right(node2, Some(node3));
        lct.splay(node3);
    }

    impl<V> Pool<Node<V>> {
        fn rotate_down(&mut self, label: Label<Node<V>>) {
            if self[label].left.is_some() {
                self.rotate_right(label);
            } else if self[label].right.is_some() {
                self.rotate_left(label);
            }
        }
    }

    #[test]
    fn basic_tree() {
        let mut lct = Pool::with_capacity(10);
        let node1 = lct.add_node("1");
        assert_eq!(lct.find_root(node1), node1);
    }

    #[test]
    fn multiple_roots() {
        let mut lct = Pool::with_capacity(10);
        let node1 = lct.add_node("1");
        let node2 = lct.add_node("2");
        assert_eq!(lct.find_root(node1), node1);
        assert_eq!(lct.find_root(node2), node2);
        assert_eq!(lct.find_root(node1), node1);
    }

    #[test]
    fn link_basic() {
tgerstel's avatar
tgerstel committed
231
        let mut lct = Pool::<Node<&str>>::with_capacity(10);
tgerstel's avatar
tgerstel committed
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
342
        let node1 = lct.add_node("1");
        let node2 = lct.add_node("2");
        lct.link(node1, node2);
        assert_eq!(lct.find_root(node1), node1, "original root changed");
        assert_eq!(lct.find_root(node2), node1, "new root not updated");
        assert_eq!(
            lct.find_root(node1),
            node1,
            "original root changed after one iteration"
        );
        assert_eq!(
            lct.find_root(node1),
            node1,
            "original root changed after repetition"
        );
        assert_eq!(lct.find_root(node2), node1, "new root unupdated");
    }

    #[test]
    fn link_multiple() {
        let mut lct = Pool::with_capacity(10);
        let node1 = lct.add_node(());
        let node2 = lct.add_node(());
        let node3 = lct.add_node(());
        lct.link(node1, node2);
        lct.link(node2, node3);
        assert_eq!(lct.find_root(node3), node1, "Didn't find grandparent");
        assert_eq!(lct.find_root(node2), node1, "Didn't find parent");
        assert_eq!(lct.find_root(node2), node1, "Didn't find itself");
    }

    #[test]
    fn many_links_to_one() {
        let mut lct = Pool::with_capacity(10);
        let node1 = lct.add_node(());
        let children = (1..6).map(|_| lct.add_node(())).collect::<Vec<_>>();
        for child in &children {
            lct.link(node1, *child);
        }

        for child in &children {
            assert_eq!(lct.find_root(*child), node1, "Wrong parent");
        }
    }

    #[test]
    fn many_links_to_one_root() {
        let mut lct = Pool::with_capacity(15);
        let root = lct.add_node(());
        let mut all_nodes = vec![root];
        let mut last_depth_nodes = vec![root];
        let mut current_depth_nodes = vec![];
        for _depth in 0..3 {
            for parent_label in &last_depth_nodes {
                for _ in 0..2 {
                    let child_label = lct.add_node(());
                    lct.link(*parent_label, child_label);
                    current_depth_nodes.push(child_label);
                    all_nodes.push(child_label);
                }
            }
            last_depth_nodes.clear();
            last_depth_nodes.append(&mut current_depth_nodes);
        }

        for node in all_nodes {
            assert_eq!(
                lct.find_root(node),
                root,
                "Failed on node: {:?}",
                lct.value(node)
            );
        }
    }

    #[test]
    fn test_cut_basic() {
        let mut lct = Pool::with_capacity(10);
        let node1 = lct.add_node(());
        let node2 = lct.add_node(());
        lct.link(node1, node2);
        assert_eq!(lct.find_root(node1), node1, "original root changed");
        assert_eq!(lct.find_root(node2), node1, "new root not updated");
        lct.cut(node2);
        assert_eq!(lct.find_root(node1), node1, "should still be its own root");
        assert_eq!(
            lct.find_root(node2),
            node2,
            "should be back to being its own root"
        );
    }

    #[test]
    fn many_cut_links() {
        let mut lct = Pool::with_capacity(10);
        let node1 = lct.add_node(());
        let children = (1..6).map(|_| lct.add_node(())).collect::<Vec<_>>();
        for child in &children {
            lct.link(node1, *child);
        }

        for child in &children {
            lct.cut(*child)
        }

        for child in &children {
            assert_eq!(lct.find_root(*child), *child, "Wrong parent");
        }
        assert_eq!(lct.find_root(node1), node1);
    }
}