LazySegmentTree

Struct LazySegmentTree 

Source
pub struct LazySegmentTree<Action>
where Action: MonoidAction,
{ /* private fields */ }
Expand description

A data structure that supports range query range update operations.

§Example

use seg_lib::{LazySegmentTree, acts::AddQueryMulUpdate};

/// Demonstrates how to use a [`LazySegmentTree`] for:
/// - range sum queries
/// - range multiplication updates
fn main() {
    // Initialize a lazy segment tree with values 0..100
    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
    assert_eq!(seg.len(), 100);
    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));

    // Apply a range update: x -> 2x
    seg.range_update(.., &2);
    assert_eq!(
        Vec::from_iter(seg.iter().copied()),
        (0..100).map(|i| i * 2).collect::<Vec<_>>()
    );

    // Query the sum over the first 50 elements
    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());

    // Update and query a single element
    seg.point_update(50, &100);
    assert_eq!(seg.point_query(50), &10_000);
}

Implementations§

Source§

impl<Action> LazySegmentTree<Action>
where Action: MonoidAction,

Source

pub fn new(n: usize) -> Self

Creates a new instance initialized with n identity elements.

If you want to initialize with specific values, use from or from_iter instead.

§Time complexity

O(N)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::new(100);
Source

pub fn len(&self) -> usize

Returns the number of elements.

§Time complexity

O(1)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::new(100);
assert_eq!(lst.len(), 100);
Examples found in repository?
examples/ex_lazy.rs (line 9)
6fn main() {
7    // Initialize a lazy segment tree with values 0..100
8    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
9    assert_eq!(seg.len(), 100);
10    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));
11
12    // Apply a range update: x -> 2x
13    seg.range_update(.., &2);
14    assert_eq!(
15        Vec::from_iter(seg.iter().copied()),
16        (0..100).map(|i| i * 2).collect::<Vec<_>>()
17    );
18
19    // Query the sum over the first 50 elements
20    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());
21
22    // Update and query a single element
23    seg.point_update(50, &100);
24    assert_eq!(seg.point_query(50), &10_000);
25}
Source

pub fn iter( &mut self, ) -> Iter<'_, <<Action as MonoidAction>::Set as Monoid>::Set>

Returns an iterator over the elements

§Time complexity

O(N)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let mut lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::new(100);
assert!(lst.iter().all(|v| v.is_none()));
Examples found in repository?
examples/ex_lazy.rs (line 10)
6fn main() {
7    // Initialize a lazy segment tree with values 0..100
8    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
9    assert_eq!(seg.len(), 100);
10    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));
11
12    // Apply a range update: x -> 2x
13    seg.range_update(.., &2);
14    assert_eq!(
15        Vec::from_iter(seg.iter().copied()),
16        (0..100).map(|i| i * 2).collect::<Vec<_>>()
17    );
18
19    // Query the sum over the first 50 elements
20    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());
21
22    // Update and query a single element
23    seg.point_update(50, &100);
24    assert_eq!(seg.point_query(50), &10_000);
25}
Source

pub fn range_update<R>( &mut self, range: R, update: &<<Action as MonoidAction>::Map as Monoid>::Set, )
where R: RangeBounds<usize>,

Updates elements over the range using the specified binary operation.

Does nothing if the range is empty.

§Time complexity

O(log N)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let mut lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::from_iter(
    std::iter::repeat_n(Some(0), 100)
);
assert_eq!(lst.range_query(..), Some(0));

lst.range_update(..75, &100);
lst.range_update(25.., &110);
assert_eq!(lst.range_query(..25), Some(100));
assert_eq!(lst.range_query(..), Some(210));
assert_eq!(lst.range_query(75..), Some(110));
Examples found in repository?
examples/ex_lazy.rs (line 13)
6fn main() {
7    // Initialize a lazy segment tree with values 0..100
8    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
9    assert_eq!(seg.len(), 100);
10    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));
11
12    // Apply a range update: x -> 2x
13    seg.range_update(.., &2);
14    assert_eq!(
15        Vec::from_iter(seg.iter().copied()),
16        (0..100).map(|i| i * 2).collect::<Vec<_>>()
17    );
18
19    // Query the sum over the first 50 elements
20    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());
21
22    // Update and query a single element
23    seg.point_update(50, &100);
24    assert_eq!(seg.point_query(50), &10_000);
25}
Source

pub fn point_update( &mut self, i: usize, update: &<<Action as MonoidAction>::Map as Monoid>::Set, )

Updates the i-th element using the specified binary operation.

§Panics

Panics if i is out of bounds.

§Time complexity

O(log N)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let mut lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::from_iter(
    std::iter::repeat_n(Some(0), 100)
);
assert_eq!(lst.range_query(..), Some(0));

lst.point_update(25, &10);
lst.point_update(75, &20);
assert_eq!(lst.range_query(..), Some(20));
assert_eq!(lst.range_query(..50), Some(10))
Examples found in repository?
examples/ex_lazy.rs (line 23)
6fn main() {
7    // Initialize a lazy segment tree with values 0..100
8    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
9    assert_eq!(seg.len(), 100);
10    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));
11
12    // Apply a range update: x -> 2x
13    seg.range_update(.., &2);
14    assert_eq!(
15        Vec::from_iter(seg.iter().copied()),
16        (0..100).map(|i| i * 2).collect::<Vec<_>>()
17    );
18
19    // Query the sum over the first 50 elements
20    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());
21
22    // Update and query a single element
23    seg.point_update(50, &100);
24    assert_eq!(seg.point_query(50), &10_000);
25}
Source

pub fn range_query<R>( &mut self, range: R, ) -> <<Action as MonoidAction>::Set as Monoid>::Set
where R: RangeBounds<usize>,

Answers a query over the range.

Returns the identity element if the range is empty.

§Time complexity

O(log N)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let mut lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::from_iter(
    (0..100).map(|v| Some(v))
);
assert_eq!(lst.range_query(..), Some(99));
assert_eq!(lst.range_query(..50), Some(49));
assert_eq!(lst.range_query(..=50), Some(50));
assert_eq!(lst.range_query(50..), Some(99));
Examples found in repository?
examples/ex_lazy.rs (line 20)
6fn main() {
7    // Initialize a lazy segment tree with values 0..100
8    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
9    assert_eq!(seg.len(), 100);
10    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));
11
12    // Apply a range update: x -> 2x
13    seg.range_update(.., &2);
14    assert_eq!(
15        Vec::from_iter(seg.iter().copied()),
16        (0..100).map(|i| i * 2).collect::<Vec<_>>()
17    );
18
19    // Query the sum over the first 50 elements
20    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());
21
22    // Update and query a single element
23    seg.point_update(50, &100);
24    assert_eq!(seg.point_query(50), &10_000);
25}
Source

pub fn point_query( &mut self, i: usize, ) -> &<<Action as MonoidAction>::Set as Monoid>::Set

Returns the result of a query for the i-th element.

§Panics

Panics if i is out of bounds.

§Time complexity

O(log N)

§Example
use seg_lib::{LazySegmentTree, acts::MaxQueryAddUpdate};

let mut lst = LazySegmentTree::<MaxQueryAddUpdate<i32>>::from_iter(
    (0..100).map(|v| Some(v))
);

for i in 0..100 {
    assert_eq!(lst.point_query(i), &Some(i as i32))
}
Examples found in repository?
examples/ex_lazy.rs (line 24)
6fn main() {
7    // Initialize a lazy segment tree with values 0..100
8    let mut seg = LazySegmentTree::<AddQueryMulUpdate<i32>>::from_iter(0..100);
9    assert_eq!(seg.len(), 100);
10    assert_eq!(Vec::from_iter(seg.iter().copied()), Vec::from_iter(0..100));
11
12    // Apply a range update: x -> 2x
13    seg.range_update(.., &2);
14    assert_eq!(
15        Vec::from_iter(seg.iter().copied()),
16        (0..100).map(|i| i * 2).collect::<Vec<_>>()
17    );
18
19    // Query the sum over the first 50 elements
20    assert_eq!(seg.range_query(..50), (0..50).map(|i| 2 * i).sum());
21
22    // Update and query a single element
23    seg.point_update(50, &100);
24    assert_eq!(seg.point_query(50), &10_000);
25}

Trait Implementations§

Source§

impl<Action> Clone for LazySegmentTree<Action>
where <<Action as MonoidAction>::Set as Monoid>::Set: Clone, <<Action as MonoidAction>::Map as Monoid>::Set: Clone, Action: MonoidAction,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Action> Debug for LazySegmentTree<Action>
where <<Action as MonoidAction>::Set as Monoid>::Set: Debug, <<Action as MonoidAction>::Map as Monoid>::Set: Debug, Action: MonoidAction,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<Action> From<Vec<<<Action as MonoidAction>::Set as Monoid>::Set>> for LazySegmentTree<Action>
where Action: MonoidAction,

Source§

fn from(values: Vec<<<Action as MonoidAction>::Set as Monoid>::Set>) -> Self

Converts to this type from the input type.
Source§

impl<Action> FromIterator<<<Action as MonoidAction>::Set as Monoid>::Set> for LazySegmentTree<Action>
where Action: MonoidAction,

Source§

fn from_iter<T: IntoIterator<Item = <<Action as MonoidAction>::Set as Monoid>::Set>>( iter: T, ) -> Self

Creates a value from an iterator. Read more

Auto Trait Implementations§

§

impl<Action> Freeze for LazySegmentTree<Action>

§

impl<Action> RefUnwindSafe for LazySegmentTree<Action>
where <<Action as MonoidAction>::Set as Monoid>::Set: RefUnwindSafe, <<Action as MonoidAction>::Map as Monoid>::Set: RefUnwindSafe,

§

impl<Action> Send for LazySegmentTree<Action>
where <<Action as MonoidAction>::Set as Monoid>::Set: Send, <<Action as MonoidAction>::Map as Monoid>::Set: Send,

§

impl<Action> Sync for LazySegmentTree<Action>
where <<Action as MonoidAction>::Set as Monoid>::Set: Sync, <<Action as MonoidAction>::Map as Monoid>::Set: Sync,

§

impl<Action> Unpin for LazySegmentTree<Action>

§

impl<Action> UnwindSafe for LazySegmentTree<Action>
where <<Action as MonoidAction>::Set as Monoid>::Set: UnwindSafe, <<Action as MonoidAction>::Map as Monoid>::Set: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.