pub struct SegTree<Spec: SegTreeSpec> { /* private fields */ }Expand description
A generic Segment Tree data structure.
A segment tree is a complete binary tree stored in a flat array that enables
efficient range queries and point updates on sequences of elements. The tree
supports any associative operation defined by the SegTreeSpec trait.
§Internal Structure
- Uses 1-based indexing where the root is at index 1
- Leaf nodes start at index
max_size(next power of 2 ≥size) - For any node at index
i, its children are at2*iand2*i+1 - Total space used is
2 * max_size
§Type Parameters
Spec- A type implementingSegTreeSpecthat defines the operation and element type
§Examples
use array_range_query::{SegTree, SegTreeSpec};
struct MaxSpec;
impl SegTreeSpec for MaxSpec {
type T = i32;
const ID: Self::T = i32::MIN;
fn op(a: &mut Self::T, b: &Self::T) { *a = (*a).max(*b); }
}
let values = vec![3, 1, 4, 1, 5, 9, 2];
let tree = SegTree::<MaxSpec>::from_vec(values);
assert_eq!(tree.query(2..5), 5); // max(4, 1, 5) = 5Implementations§
Source§impl<Spec: SegTreeSpec> SegTree<Spec>
impl<Spec: SegTreeSpec> SegTree<Spec>
Sourcepub fn from_slice(values: &[Spec::T]) -> Self
pub fn from_slice(values: &[Spec::T]) -> Self
Sourcepub fn query<R: RangeBounds<usize>>(&self, range: R) -> Spec::T
pub fn query<R: RangeBounds<usize>>(&self, range: R) -> Spec::T
Sourcepub fn update(&mut self, index: usize, value: Spec::T)
pub fn update(&mut self, index: usize, value: Spec::T)
Updates the value at the given index.
§Example
use array_range_query::helpers::SegTreeMax;
let mut tree = SegTreeMax::<i32>::from_vec(vec![1, 2, 3, 4, 5]);
assert_eq!(tree.query(..), 5);
tree.update(2, 6);
assert_eq!(tree.query(..), 6);§Time Complexity
O(log n)
§Panics
Panics if index is out of bounds.
Auto Trait Implementations§
impl<Spec> Freeze for SegTree<Spec>
impl<Spec> RefUnwindSafe for SegTree<Spec>
impl<Spec> Send for SegTree<Spec>
impl<Spec> Sync for SegTree<Spec>
impl<Spec> Unpin for SegTree<Spec>where
Spec: Unpin,
impl<Spec> UnwindSafe for SegTree<Spec>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more