Skip to content

Commit

Permalink
segtree: FromIterator
Browse files Browse the repository at this point in the history
  • Loading branch information
mizar committed Apr 16, 2023
1 parent a04c1ef commit 764c814
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/segtree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::internal_bit::ceil_pow2;
use crate::internal_type_traits::{BoundedAbove, BoundedBelow, One, Zero};
use std::cmp::{max, min};
use std::convert::Infallible;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::ops::{Add, BitAnd, BitOr, BitXor, Bound, Mul, Not, RangeBounds};

Expand Down Expand Up @@ -134,6 +135,26 @@ impl<M: Monoid> From<Vec<M::S>> for Segtree<M> {
ret
}
}
impl<M: Monoid> FromIterator<M::S> for Segtree<M> {
fn from_iter<T: IntoIterator<Item = M::S>>(iter: T) -> Self {
let iter = iter.into_iter();
let n = iter.size_hint().0;
let log = ceil_pow2(n as u32) as usize;
let size = 1 << log;
let mut d = Vec::with_capacity(size * 2);
d.extend(
std::iter::repeat_with(M::identity)
.take(size)
.chain(iter)
.chain(std::iter::repeat_with(M::identity).take(size - n)),
);
let mut ret = Segtree { n, size, log, d };
for i in (1..size).rev() {
ret.update(i);
}
ret
}
}
impl<M: Monoid> Segtree<M> {
pub fn set(&mut self, mut p: usize, x: M::S) {
assert!(p < self.n);
Expand Down

0 comments on commit 764c814

Please sign in to comment.