-
Notifications
You must be signed in to change notification settings - Fork 522
/
persistent_tree.rs
84 lines (76 loc) · 2.29 KB
/
persistent_tree.rs
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
use std::rc::Rc;
pub struct Node {
left: Option<Rc<Node>>,
right: Option<Rc<Node>>,
sum: i32,
}
impl Node {
fn new(sum: i32) -> Self {
Self {
left: None,
right: None,
sum,
}
}
fn new_parent(left: &Rc<Node>, right: &Rc<Node>) -> Self {
Self {
left: Some(left.clone()),
right: Some(right.clone()),
sum: left.sum + right.sum,
}
}
}
pub struct PersistentTree;
impl PersistentTree {
pub fn build(left: i32, right: i32) -> Rc<Node> {
let node = if left == right {
Node::new(0)
} else {
let mid = (left + right) >> 1;
Node::new_parent(&Self::build(left, mid), &Self::build(mid + 1, right))
};
Rc::new(node)
}
pub fn sum(from: i32, to: i32, root: &Node, left: i32, right: i32) -> i32 {
if from > right || left > to {
0
} else if from <= left && right <= to {
root.sum
} else {
let mid = (left + right) >> 1;
Self::sum(from, to, root.left.as_ref().unwrap(), left, mid)
+ Self::sum(from, to, root.right.as_ref().unwrap(), mid + 1, right)
}
}
pub fn set(pos: i32, value: i32, root: &Node, left: i32, right: i32) -> Rc<Node> {
let node = if left == right {
Node::new(value)
} else {
let mid = (left + right) >> 1;
if pos <= mid {
Node::new_parent(
&Self::set(pos, value, root.left.as_ref().unwrap(), left, mid),
root.right.as_ref().unwrap(),
)
} else {
Node::new_parent(
root.left.as_ref().unwrap(),
&Self::set(pos, value, root.right.as_ref().unwrap(), mid + 1, right),
)
}
};
Rc::new(node)
}
}
#[cfg(test)]
mod tests {
use crate::structures::persistent_tree::PersistentTree;
#[test]
fn basic_test() {
let n = 10;
let t1 = PersistentTree::build(0, n - 1);
let t2 = PersistentTree::set(0, 1, &t1, 0, n - 1);
assert_eq!(PersistentTree::sum(0, n - 1, &t1, 0, n - 1), 0);
assert_eq!(PersistentTree::sum(0, n - 1, &t2, 0, n - 1), 1);
}
}