├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── fenwick.rs ├── lib.rs ├── maybe_owned.rs ├── ops ├── mod.rs └── num.rs ├── propagating.rs └── segment_tree.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "segment-tree" 3 | version = "2.0.0" 4 | authors = ["Alice Ryhl "] 5 | description = "Quickly perform interval queries or modifications." 6 | repository = "https://github.com/Darksonn/segment-tree" 7 | readme = "README.md" 8 | keywords = ["segment", "sum", "query", "interval", "fenwick"] 9 | categories = ["data-structures", "algorithms"] 10 | license = "MIT" 11 | edition = "2018" 12 | 13 | [dependencies] 14 | num-bigint = { version = "~0.2.0", optional = true } 15 | 16 | [dev-dependencies] 17 | rand = "0.6" 18 | 19 | [package.metadata.docs.rs] 20 | features = ["num-bigint"] 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017, 2018 Alice Ryhl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # segment-tree 2 | 3 | [![Documentation](https://docs.rs/segment-tree/badge.svg)](https://docs.rs/segment-tree) 4 | [![Cargo](https://img.shields.io/crates/v/segment-tree.svg)](https://crates.io/crates/segment-tree) 5 | [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Darksonn/segment-tree/blob/master/LICENSE) 6 | 7 | This crate contains various data structures useful for quickly performing 8 | interval queries or modifications in some array. 9 | 10 | The data structures in this crate are all trees. The trees are represented using 11 | an array for high performance and low memory usage. Despite the name of the 12 | crate, not every tree in this crate is a segment tree. 13 | 14 | ## Cargo.toml 15 | 16 | ```toml 17 | [dependencies] 18 | segment-tree = "2" 19 | ``` 20 | 21 | ## Example 22 | 23 | The example below shows a segment tree, which allows queries to any interval in logaritmic 24 | time. 25 | 26 | ```rust 27 | use segment_tree::SegmentPoint; 28 | use segment_tree::ops::Min; 29 | 30 | let array = vec![4, 3, 2, 1, 2, 3, 4]; 31 | let mut tree = SegmentPoint::build(array, Min); 32 | 33 | // Compute the minimum of the whole array. 34 | assert_eq!(tree.query(0, tree.len()), 1); 35 | 36 | // Compute the minimum of part of the array. 37 | assert_eq!(tree.query(0, 3), 2); 38 | 39 | // Change the 1 into a 10. 40 | tree.modify(3, 10); 41 | 42 | // The minimum of the whole array is now 2. 43 | assert_eq!(tree.query(0, tree.len()), 2); 44 | ``` 45 | 46 | This crate also has a [`PointSegment`][1] type, which instead allows modifications to 47 | intervals. 48 | 49 | The related crate [`prefix_sum`][2] might also be of interest. 50 | 51 | [1]: https://docs.rs/segment-tree/2/segment_tree/struct.PointSegment.html 52 | [2]: https://crates.io/crates/prefix-sum 53 | -------------------------------------------------------------------------------- /src/fenwick.rs: -------------------------------------------------------------------------------- 1 | use crate::ops::{Commutative, Invertible}; 2 | use crate::maybe_owned::MaybeOwned; 3 | 4 | use std::default::Default; 5 | use std::hash::{Hash, Hasher}; 6 | 7 | /// This data structure allows prefix queries and single element modification. 8 | /// 9 | /// This tree allocates `n * sizeof(N)` bytes of memory, and can be resized. 10 | /// 11 | /// This data structure is implemented using a [Fenwick tree][1], which is also known as a 12 | /// binary indexed tree. 13 | /// 14 | /// The similar crate [`prefix-sum`] might also be of interest. 15 | /// 16 | /// # Examples 17 | /// 18 | /// Showcase of functionality: 19 | /// 20 | /// ```rust 21 | /// use segment_tree::ops::Add; 22 | /// use segment_tree::PrefixPoint; 23 | /// 24 | /// let buf = vec![10, 5, 30, 40]; 25 | /// 26 | /// let mut pp = PrefixPoint::build(buf, Add); 27 | /// 28 | /// // If we query, we get the sum up until the specified value. 29 | /// assert_eq!(pp.query(0), 10); 30 | /// assert_eq!(pp.query(1), 15); 31 | /// assert_eq!(pp.query(2), 45); 32 | /// assert_eq!(pp.query(3), 85); 33 | /// 34 | /// // Add five to the second value. 35 | /// pp.modify(1, 5); 36 | /// assert_eq!(pp.query(0), 10); 37 | /// assert_eq!(pp.query(1), 20); 38 | /// assert_eq!(pp.query(2), 50); 39 | /// assert_eq!(pp.query(3), 90); 40 | /// 41 | /// // Multiply every value with 2. 42 | /// pp.map(|v| *v *= 2); 43 | /// assert_eq!(pp.query(0), 20); 44 | /// assert_eq!(pp.query(1), 40); 45 | /// assert_eq!(pp.query(2), 100); 46 | /// assert_eq!(pp.query(3), 180); 47 | /// 48 | /// // Divide with two to undo. 49 | /// pp.map(|v| *v /= 2); 50 | /// // Add some more values. 51 | /// pp.extend(vec![0, 10].into_iter()); 52 | /// assert_eq!(pp.query(0), 10); 53 | /// assert_eq!(pp.query(1), 20); 54 | /// assert_eq!(pp.query(2), 50); 55 | /// assert_eq!(pp.query(3), 90); 56 | /// assert_eq!(pp.query(4), 90); 57 | /// assert_eq!(pp.query(5), 100); 58 | /// 59 | /// // Get the underlying values. 60 | /// assert_eq!(pp.get(0), 10); 61 | /// assert_eq!(pp.get(1), 10); 62 | /// assert_eq!(pp.get(2), 30); 63 | /// assert_eq!(pp.get(3), 40); 64 | /// assert_eq!(pp.get(4), 0); 65 | /// assert_eq!(pp.get(5), 10); 66 | /// 67 | /// // Remove the last value 68 | /// pp.truncate(5); 69 | /// assert_eq!(pp.get(0), 10); 70 | /// assert_eq!(pp.get(1), 10); 71 | /// assert_eq!(pp.get(2), 30); 72 | /// assert_eq!(pp.get(3), 40); 73 | /// assert_eq!(pp.get(4), 0); 74 | /// 75 | /// // Get back the original values. 76 | /// assert_eq!(pp.unwrap(), vec![10, 10, 30, 40, 0]); 77 | /// ``` 78 | /// 79 | /// You can also use other operators: 80 | /// 81 | /// ```rust 82 | /// use segment_tree::ops::Mul; 83 | /// use segment_tree::PrefixPoint; 84 | /// 85 | /// let buf = vec![10, 5, 30, 40]; 86 | /// 87 | /// let mut pp = PrefixPoint::build(buf, Mul); 88 | /// 89 | /// assert_eq!(pp.query(0), 10); 90 | /// assert_eq!(pp.query(1), 50); 91 | /// assert_eq!(pp.query(2), 1500); 92 | /// assert_eq!(pp.query(3), 60000); 93 | /// ``` 94 | /// 95 | /// [1]: https://en.wikipedia.org/wiki/Fenwick_tree 96 | /// [`prefix-sum`]: https://crates.io/crates/prefix-sum 97 | pub struct PrefixPoint where O: Commutative { 98 | buf: Vec, 99 | op: O 100 | } 101 | 102 | /// Returns the least significant bit that is one. 103 | #[inline(always)] 104 | fn lsb(i: usize) -> usize { 105 | i & (1 + !i) 106 | } 107 | 108 | /// Could also be done with slice_at_mut, but that's a giant pain 109 | #[inline(always)] 110 | unsafe fn combine_mut>(buf: &mut Vec, i: usize, j: usize, op: &O) { 111 | debug_assert!(i != j); 112 | let ptr1 = &mut buf[i] as *mut N; 113 | let ptr2 = &buf[j] as *const N; 114 | op.combine_mut(&mut *ptr1, &*ptr2); 115 | } 116 | /// Could also be done with slice_at_mut, but that's a giant pain 117 | #[inline(always)] 118 | unsafe fn uncombine_mut>(buf: &mut Vec, i: usize, j: usize, op: &O) { 119 | debug_assert!(i != j); 120 | let ptr1 = &mut buf[i] as *mut N; 121 | let ptr2 = &buf[j] as *const N; 122 | op.uncombine(&mut *ptr1, &*ptr2); 123 | } 124 | 125 | impl> PrefixPoint { 126 | /// Creates a `PrefixPoint` containing the given values. 127 | /// Uses `O(len)` time. 128 | pub fn build(mut buf: Vec, op: O) -> PrefixPoint { 129 | let len = buf.len(); 130 | for i in 0..len { 131 | let j = i + lsb(i+1); 132 | if j < len { 133 | unsafe { 134 | combine_mut::(&mut buf, j, i, &op); 135 | } 136 | } 137 | } 138 | PrefixPoint { buf: buf, op: op } 139 | } 140 | /// Returns the number of values in this tree. 141 | /// Uses `O(1)` time. 142 | pub fn len(&self) -> usize { 143 | self.buf.len() 144 | } 145 | /// Computes `a[0] * a[1] * ... * a[i]`. Note that `i` is inclusive. 146 | /// Uses `O(log(i))` time. 147 | #[inline] 148 | pub fn query(&self, mut i: usize) -> N where N: Clone { 149 | let mut sum = self.buf[i].clone(); 150 | i -= lsb(1+i) - 1; 151 | while i > 0 { 152 | sum = self.op.combine_left(sum, &self.buf[i-1]); 153 | i -= lsb(i); 154 | } 155 | sum 156 | } 157 | /// Computes `a[0] * a[1] * ... * a[i]`. Note that `i` is inclusive. 158 | /// Uses `O(log(i))` time. 159 | #[inline] 160 | pub fn query_noclone(&self, mut i: usize) -> MaybeOwned { 161 | let mut sum = MaybeOwned::Borrowed(&self.buf[i]); 162 | i -= lsb(1+i) - 1; 163 | while i > 0 { 164 | sum = MaybeOwned::Owned(match sum { 165 | MaybeOwned::Borrowed(ref v) => self.op.combine(v, &self.buf[i-1]), 166 | MaybeOwned::Owned(v) => self.op.combine_left(v, &self.buf[i-1]), 167 | }); 168 | i -= lsb(i); 169 | } 170 | sum 171 | } 172 | /// Combine the value at `i` with `delta`. 173 | /// Uses `O(log(len))` time. 174 | #[inline] 175 | pub fn modify(&mut self, mut i: usize, delta: N) { 176 | let len = self.len(); 177 | while i < len { 178 | self.op.combine_mut(&mut self.buf[i], &delta); 179 | i += lsb(i+1); 180 | } 181 | } 182 | /// Truncates the `PrefixPoint` to the given size. If `size >= len`, this method does 183 | /// nothing. Uses `O(1)` time. 184 | #[inline(always)] 185 | pub fn truncate(&mut self, size: usize) { 186 | self.buf.truncate(size); 187 | } 188 | /// Calls `shrink_to_fit` on the interval vector. 189 | #[inline(always)] 190 | pub fn shrink_to_fit(&mut self) { 191 | self.buf.shrink_to_fit(); 192 | } 193 | /// Replace every value in the type with `f(value)`. 194 | /// This function assumes that `combine(f(a), f(b)) = f(combine(a, b))`. 195 | /// 196 | /// The function is applied `len` times. 197 | #[inline] 198 | pub fn map(&mut self, mut f: F) { 199 | for val in &mut self.buf { 200 | f(val); 201 | } 202 | } 203 | } 204 | impl> Extend for PrefixPoint { 205 | /// Adds the given values to the `PrefixPoint`, increasing its size. 206 | /// Uses `O(len)` time. 207 | fn extend>(&mut self, values: I) { 208 | let oldlen = self.len(); 209 | self.buf.extend(values); 210 | let len = self.len(); 211 | for i in 0..len { 212 | let j = i + lsb(i+1); 213 | if oldlen <= j && j < len { 214 | unsafe { 215 | combine_mut::(&mut self.buf, j, i, &self.op); 216 | } 217 | } 218 | } 219 | } 220 | } 221 | impl + Invertible> PrefixPoint { 222 | /// Returns the value at `i`. 223 | /// Uses `O(log(i))` time. 224 | /// Store your own copy of the array if you want constant time. 225 | pub fn get(&self, mut i: usize) -> N where N: Clone { 226 | let mut sum = self.buf[i].clone(); 227 | let z = 1 + i - lsb(i+1); 228 | while i != z { 229 | self.op.uncombine(&mut sum, &self.buf[i-1]); 230 | i -= lsb(i); 231 | } 232 | sum 233 | } 234 | /// Change the value at the index to be the specified value. 235 | /// Uses `O(log(i))` time. 236 | pub fn set(&mut self, i: usize, mut value: N) where N: Clone { 237 | let current = self.get(i); 238 | self.op.uncombine(&mut value, ¤t); 239 | self.modify(i, value); 240 | } 241 | /// Compute the underlying array of values. 242 | /// Uses `O(len)` time. 243 | pub fn unwrap(self) -> Vec { 244 | let mut buf = self.buf; 245 | let len = buf.len(); 246 | for i in (0..len).rev() { 247 | let j = i + lsb(i+1); 248 | if j < len { 249 | unsafe { 250 | uncombine_mut::(&mut buf, j, i, &self.op); 251 | } 252 | } 253 | } 254 | buf 255 | } 256 | /// Compute the underlying array of values. 257 | /// Uses `O(len)` time. 258 | pub fn unwrap_clone(&self) -> Vec where N: Clone { 259 | let len = self.buf.len(); 260 | let mut buf = self.buf.clone(); 261 | for i in (0..len).rev() { 262 | let j = i + lsb(i+1); 263 | if j < len { 264 | unsafe { 265 | uncombine_mut::(&mut buf, j, i, &self.op); 266 | } 267 | } 268 | } 269 | buf 270 | } 271 | } 272 | 273 | impl + Clone> Clone for PrefixPoint { 274 | fn clone(&self) -> PrefixPoint { 275 | PrefixPoint { 276 | buf: self.buf.clone(), op: self.op.clone() 277 | } 278 | } 279 | } 280 | impl + Default> Default for PrefixPoint { 281 | #[inline] 282 | fn default() -> PrefixPoint { 283 | PrefixPoint { buf: Vec::new(), op: Default::default() } 284 | } 285 | } 286 | impl<'a, N: 'a + Hash, O: Commutative> Hash for PrefixPoint { 287 | #[inline] 288 | fn hash(&self, state: &mut H) { 289 | self.buf.hash(state); 290 | } 291 | } 292 | 293 | #[cfg(test)] 294 | mod tests { 295 | 296 | /// Modifies the given slice such that the n'th element becomes the sum of the first n 297 | /// elements. 298 | pub fn compute_prefix_sum + Copy>(buf: &mut[N]) { 299 | let mut iter = buf.iter_mut(); 300 | match iter.next() { 301 | None => {}, 302 | Some(s) => { 303 | let mut sum = *s; 304 | for item in iter { 305 | sum = sum + *item; 306 | *item = sum; 307 | } 308 | } 309 | } 310 | } 311 | 312 | use super::*; 313 | use rand::distributions::Standard; 314 | use rand::prelude::*; 315 | use std::num::Wrapping; 316 | use crate::ops::Add; 317 | 318 | fn random_vec(rng: &mut ThreadRng, len: usize) -> Vec> { 319 | rng.sample_iter(&Standard).map(|i| Wrapping(i)).take(len).collect() 320 | } 321 | 322 | #[test] 323 | fn fenwick_query() { 324 | let mut rng = thread_rng(); 325 | for n in 0..130 { 326 | let mut vec = random_vec(&mut rng, n); 327 | let fenwick = PrefixPoint::build(vec.clone(), Add); 328 | compute_prefix_sum(&mut vec); 329 | for i in 0..vec.len() { 330 | assert_eq!(vec[i], fenwick.query(i)); 331 | assert_eq!(&vec[i], fenwick.query_noclone(i).borrow()); 332 | } 333 | } 334 | } 335 | #[test] 336 | fn fenwick_map() { 337 | let mut rng = thread_rng(); 338 | for n in 0..130 { 339 | let mut vec = random_vec(&mut rng, n); 340 | let mut fenwick = PrefixPoint::build(vec.clone(), Add); 341 | assert_eq!(fenwick.clone().unwrap(), vec); 342 | assert_eq!(fenwick.clone().unwrap_clone(), vec); 343 | compute_prefix_sum(&mut vec); 344 | fenwick.map(|n| *n = Wrapping(12) * *n); 345 | for i in 0..vec.len() { 346 | assert_eq!(vec[i]*Wrapping(12), fenwick.query(i)); 347 | } 348 | } 349 | } 350 | #[test] 351 | fn fenwick_modify() { 352 | let mut rng = thread_rng(); 353 | for n in 0..130 { 354 | let mut vec = random_vec(&mut rng, n); 355 | let diff = random_vec(&mut rng, n); 356 | let mut fenwick = PrefixPoint::build(vec.clone(), Add); 357 | for i in 0..diff.len() { 358 | let mut ps: Vec> = vec.clone(); 359 | compute_prefix_sum(&mut ps); 360 | assert_eq!(fenwick.clone().unwrap(), vec); 361 | assert_eq!(fenwick.clone().unwrap_clone(), vec); 362 | for j in 0..vec.len() { 363 | assert_eq!(ps[j], fenwick.query(j)); 364 | assert_eq!(vec[j], fenwick.get(j)); 365 | } 366 | vec[i] += diff[i]; 367 | fenwick.modify(i, diff[i]); 368 | } 369 | } 370 | } 371 | #[test] 372 | fn fenwick_set() { 373 | let mut rng = thread_rng(); 374 | for n in 0..130 { 375 | let mut vec = random_vec(&mut rng, n); 376 | let diff = random_vec(&mut rng, n); 377 | let mut fenwick = PrefixPoint::build(vec.clone(), Add); 378 | for i in 0..diff.len() { 379 | let mut ps: Vec> = vec.clone(); 380 | compute_prefix_sum(&mut ps); 381 | assert_eq!(fenwick.clone().unwrap(), vec); 382 | assert_eq!(fenwick.clone().unwrap_clone(), vec); 383 | for j in 0..vec.len() { 384 | assert_eq!(ps[j], fenwick.query(j)); 385 | assert_eq!(vec[j], fenwick.get(j)); 386 | } 387 | vec[i] = diff[i]; 388 | fenwick.set(i, diff[i]); 389 | } 390 | } 391 | } 392 | #[test] 393 | fn fenwick_extend() { 394 | let mut rng = thread_rng(); 395 | for n in 0..130 { 396 | let vec = random_vec(&mut rng, n); 397 | let mut sum = vec.clone(); 398 | compute_prefix_sum(&mut sum); 399 | for i in 0..sum.len() { 400 | let mut fenwick = PrefixPoint::build(vec.iter().take(i/2).map(|&i| i).collect(), Add); 401 | fenwick.extend(vec.iter().skip(i/2).take(i - i/2).map(|&i| i)); 402 | for j in 0..i { 403 | assert_eq!(sum[j], fenwick.query(j)); 404 | } 405 | } 406 | } 407 | } 408 | } 409 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate contains various data structures useful for quickly performing interval 2 | //! queries or modifications in some array. 3 | //! 4 | //! The data structures in this crate are all trees. The trees are represented using an 5 | //! array for high performance and low memory usage. 6 | //! Despite the name of the crate, not every tree in this crate is a segment tree. 7 | //! 8 | //! The [`SegmentPoint`] data structure allows interval queries and point updates to an 9 | //! array in logaritmic time. It is well known for solving the [range minimum query][1] 10 | //! problem. This is the data structure traditionally known as a segment tree. 11 | //! 12 | //! The [`PointSegment`] data structure allows point queries and interval updates to an 13 | //! array in logaritmic time. 14 | //! 15 | //! The [`PrefixPoint`] data structure is a weaker version of the [`SegmentPoint`] data 16 | //! structure, since the intervals must start at the index `0` and the operator must be 17 | //! [commutative][2]. However it has the advantage that it uses half the memory and the 18 | //! size of the array can be changed. This data structure is also known as a 19 | //! [fenwick tree][3]. 20 | //! 21 | //! The segment tree in this crate is inspired by [this blog post][4]. 22 | //! 23 | //! The similar crate [`prefix-sum`] might also be of interest. 24 | //! 25 | //! This crate has the optional feature [`num-bigint`], which implements the operations in 26 | //! [`ops`] for [`BigInt`] and [`BigUint`]. 27 | //! 28 | //! # Example 29 | //! 30 | //! The example below shows a segment tree, which allows queries to any interval in 31 | //! logaritmic time. 32 | //! 33 | //! ``` 34 | //! use segment_tree::SegmentPoint; 35 | //! use segment_tree::ops::Min; 36 | //! 37 | //! let array = vec![4, 3, 2, 1, 2, 3, 4]; 38 | //! let mut tree = SegmentPoint::build(array, Min); 39 | //! 40 | //! // Compute the minimum of the whole array. 41 | //! assert_eq!(tree.query(0, tree.len()), 1); 42 | //! 43 | //! // Compute the minimum of part of the array. 44 | //! assert_eq!(tree.query(0, 3), 2); 45 | //! 46 | //! // Change the 1 into a 10. 47 | //! tree.modify(3, 10); 48 | //! 49 | //! // The minimum of the whole array is now 2. 50 | //! assert_eq!(tree.query(0, tree.len()), 2); 51 | //! ``` 52 | //! 53 | //! [1]: https://en.wikipedia.org/wiki/Range_minimum_query 54 | //! [2]: ops/trait.Commutative.html 55 | //! [3]: https://en.wikipedia.org/wiki/Fenwick_tree 56 | //! [4]: https://codeforces.com/blog/entry/18051 57 | //! [`SegmentPoint`]: struct.SegmentPoint.html 58 | //! [`PointSegment`]: struct.PointSegment.html 59 | //! [`PrefixPoint`]: struct.PrefixPoint.html 60 | //! [`num-bigint`]: https://crates.io/crates/num-bigint 61 | //! [`BigInt`]: https://docs.rs/num-bigint/0.2/num_bigint/struct.BigInt.html 62 | //! [`BigUint`]: https://docs.rs/num-bigint/0.2/num_bigint/struct.BigUint.html 63 | //! [`prefix-sum`]: https://crates.io/crates/prefix-sum 64 | //! [`ops`]: ops/index.html 65 | 66 | pub mod ops; 67 | pub mod maybe_owned; 68 | pub use crate::fenwick::PrefixPoint; 69 | pub use crate::propagating::PointSegment; 70 | pub use crate::segment_tree::SegmentPoint; 71 | 72 | mod fenwick; 73 | mod propagating; 74 | mod segment_tree; 75 | -------------------------------------------------------------------------------- /src/maybe_owned.rs: -------------------------------------------------------------------------------- 1 | //! This module contains a variant of [`Cow`] that doesn't require [`Clone`]. 2 | //! 3 | //! [`Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html 4 | //! [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html 5 | 6 | use std::cmp; 7 | use std::fmt::{self, Debug, Display, Formatter}; 8 | use std::default::Default; 9 | use std::hash::{Hash, Hasher}; 10 | use std::borrow::Cow; 11 | 12 | /// A variant of [`Cow`] that doesn't require [`Clone`]. 13 | /// 14 | /// [`Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html 15 | /// [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html 16 | pub enum MaybeOwned<'a, T: 'a> { 17 | Borrowed(&'a T), 18 | Owned(T) 19 | } 20 | 21 | impl<'a, T: 'a> MaybeOwned<'a, T> { 22 | /// Get a reference to the contained value. 23 | #[inline] 24 | pub fn borrow(&self) -> &T { 25 | match *self { 26 | MaybeOwned::Borrowed(v) => v, 27 | MaybeOwned::Owned(ref v) => &v 28 | } 29 | } 30 | /// Turn this type into a [`Cow`]. 31 | /// 32 | /// Requires [`Clone`]. 33 | /// 34 | /// [`Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html 35 | /// [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html 36 | #[inline] 37 | pub fn into_cow(self) -> Cow<'a, T> where T: Clone { 38 | match self { 39 | MaybeOwned::Borrowed(v) => Cow::Borrowed(v), 40 | MaybeOwned::Owned(v) => Cow::Owned(v), 41 | } 42 | } 43 | } 44 | 45 | impl<'a, T: 'a + Clone> MaybeOwned<'a, T> { 46 | /// Get the value, cloning if necessary. 47 | #[inline] 48 | pub fn unwrap_or_clone(self) -> T { 49 | match self { 50 | MaybeOwned::Borrowed(v) => v.clone(), 51 | MaybeOwned::Owned(v) => v 52 | } 53 | } 54 | } 55 | 56 | impl<'a, T: 'a + Debug> Debug for MaybeOwned<'a, T> { 57 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 58 | match *self { 59 | MaybeOwned::Borrowed(v) => write!(f, "Borrw({:?})", v), 60 | MaybeOwned::Owned(ref v) => write!(f, "Owned({:?})", v), 61 | } 62 | } 63 | } 64 | 65 | impl<'a, T: 'a + Display> Display for MaybeOwned<'a, T> { 66 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 67 | match *self { 68 | MaybeOwned::Borrowed(v) => v.fmt(f), 69 | MaybeOwned::Owned(ref v) => v.fmt(f), 70 | } 71 | } 72 | } 73 | 74 | impl<'a, T: 'a + PartialEq> cmp::PartialEq for MaybeOwned<'a, T> { 75 | #[inline] 76 | fn eq(&self, other: &MaybeOwned) -> bool { 77 | self.borrow().eq(other.borrow()) 78 | } 79 | #[inline] 80 | fn ne(&self, other: &MaybeOwned) -> bool { 81 | self.borrow().ne(other.borrow()) 82 | } 83 | } 84 | impl<'a, T: 'a + Eq> cmp::Eq for MaybeOwned<'a, T> { } 85 | 86 | impl<'a, T: 'a + PartialOrd> cmp::PartialOrd for MaybeOwned<'a, T> { 87 | #[inline] 88 | fn partial_cmp(&self, other: &MaybeOwned) -> Option { 89 | self.borrow().partial_cmp(other.borrow()) 90 | } 91 | #[inline] 92 | fn lt(&self, other: &MaybeOwned) -> bool { 93 | self.borrow().lt(other.borrow()) 94 | } 95 | #[inline] 96 | fn le(&self, other: &MaybeOwned) -> bool { 97 | self.borrow().le(other.borrow()) 98 | } 99 | #[inline] 100 | fn gt(&self, other: &MaybeOwned) -> bool { 101 | self.borrow().gt(other.borrow()) 102 | } 103 | #[inline] 104 | fn ge(&self, other: &MaybeOwned) -> bool { 105 | self.borrow().ge(other.borrow()) 106 | } 107 | } 108 | impl<'a, T: 'a + Ord> cmp::Ord for MaybeOwned<'a, T> { 109 | #[inline] 110 | fn cmp(&self, other: &MaybeOwned) -> cmp::Ordering { 111 | self.borrow().cmp(other.borrow()) 112 | } 113 | } 114 | 115 | impl<'a, T: 'a + Default> Default for MaybeOwned<'a, T> { 116 | #[inline] 117 | fn default() -> MaybeOwned<'a, T> { 118 | MaybeOwned::Owned(Default::default()) 119 | } 120 | } 121 | 122 | impl<'a, T: 'a + Hash> Hash for MaybeOwned<'a, T> { 123 | #[inline] 124 | fn hash(&self, state: &mut H) { 125 | self.borrow().hash(state) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/ops/mod.rs: -------------------------------------------------------------------------------- 1 | //! Module of operations that can be performed in a segment tree. 2 | //! 3 | //! A segment tree needs some operation, and this module contains the main [`Operation`] 4 | //! trait, together with the marker trait [`Commutative`]. This module also contains 5 | //! implementations for simple operations. 6 | //! 7 | //! [`Operation`]: trait.Operation.html 8 | //! [`Commutative`]: trait.Commutative.html 9 | 10 | use std::num::Wrapping; 11 | 12 | #[cfg(feature = "num-bigint")] 13 | mod num; 14 | 15 | /// A trait that specifies which associative operator to use in a segment tree. 16 | pub trait Operation { 17 | /// The operation that is performed to combine two intervals in the segment tree. 18 | /// 19 | /// This function must be [associative][1], that is `combine(combine(a, b), c) = 20 | /// combine(a, combine(b, c))`. 21 | /// 22 | /// [1]: https://en.wikipedia.org/wiki/Associative_property 23 | fn combine(&self, a: &N, b: &N) -> N; 24 | /// Replace the value in `a` with `combine(a, b)`. This function exists to allow 25 | /// certain optimizations and by default simply calls `combine`. 26 | #[inline] 27 | fn combine_mut(&self, a: &mut N, b: &N) { 28 | let res = self.combine(&*a, b); 29 | *a = res; 30 | } 31 | /// Replace the value in `b` with `combine(a, b)`. This function exists to allow 32 | /// certain optimizations and by default simply calls `combine`. 33 | #[inline] 34 | fn combine_mut2(&self, a: &N, b: &mut N) { 35 | let res = self.combine(a, &*b); 36 | *b = res; 37 | } 38 | /// Must return the same as `combine`. This function exists to allow certain 39 | /// optimizations and by default simply calls `combine_mut`. 40 | #[inline] 41 | fn combine_left(&self, mut a: N, b: &N) -> N { 42 | self.combine_mut(&mut a, b); a 43 | } 44 | /// Must return the same as `combine`. This function exists to allow certain 45 | /// optimizations and by default simply calls `combine_mut2`. 46 | #[inline] 47 | fn combine_right(&self, a: &N, mut b: N) -> N { 48 | self.combine_mut2(a, &mut b); b 49 | } 50 | /// Must return the same as `combine`. This function exists to allow certain 51 | /// optimizations and by default simply calls `combine_left`. 52 | #[inline] 53 | fn combine_both(&self, a: N, b: N) -> N { 54 | self.combine_left(a, &b) 55 | } 56 | } 57 | 58 | /// A marker trait that specifies that an [`Operation`] is [commutative][1], that is: 59 | /// `combine(a, b) = combine(b, a)`. 60 | /// 61 | /// [`Operation`]: trait.Operation.html 62 | /// [1]: https://en.wikipedia.org/wiki/Commutative_property 63 | pub trait Commutative: Operation {} 64 | 65 | /// A trait that specifies that this [`Operation`] has an [identity element][1]. 66 | /// 67 | /// An identity must satisfy `combine(a, id) = a` and `combine(id, a) = a`, where `id` is 68 | /// something returned by [`identity`]. 69 | /// 70 | /// [`Operation`]: trait.Operation.html 71 | /// [`identity`]: #tymethod.identity 72 | /// [1]: https://en.wikipedia.org/wiki/Identity_element 73 | pub trait Identity { 74 | /// Returns an element such that if [combined][1] with any element `a` the result must 75 | /// be `a`. 76 | /// 77 | /// [1]: trait.Operation.html#tymethod.combine 78 | fn identity(&self) -> N; 79 | } 80 | 81 | /// A trait for invertible operations. 82 | pub trait Invertible { 83 | /// A method such that the following code will leave `a` in the same state as it 84 | /// started. 85 | /// 86 | ///```rust 87 | ///# use segment_tree::ops::{Add, Operation, Invertible}; 88 | ///# let op = Add; 89 | ///# let mut a = 1i32; 90 | ///# let mut original_value_of_a = 1i32; 91 | ///# let mut b = 2i32; 92 | /// // after running these two methods, a should be unchanged: 93 | ///op.combine_mut(&mut a, &b); 94 | ///op.uncombine(&mut a, &b); 95 | ///assert_eq!(a, original_value_of_a); 96 | /// // a should also be unchanged after running them in the reverse order 97 | ///op.uncombine(&mut a, &b); 98 | ///op.combine_mut(&mut a, &b); 99 | ///assert_eq!(a, original_value_of_a); 100 | ///``` 101 | fn uncombine(&self, a: &mut N, b: &N); 102 | } 103 | 104 | /// Each node contains the sum of the interval it represents. 105 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 106 | pub struct Add; 107 | /// Each node contains the product of the interval it represents. 108 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 109 | pub struct Mul; 110 | 111 | 112 | /// Each node contains the bitwise and of the interval it represents. 113 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 114 | pub struct And; 115 | /// Each node contains the bitwise or of the interval it represents. 116 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 117 | pub struct Or; 118 | /// Each node contains the bitwise xor of the interval it represents. 119 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 120 | pub struct Xor; 121 | 122 | /// Each node contains the minimum of the interval it represents. 123 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 124 | pub struct Min; 125 | /// Each node contains the maximum of the interval it represents. 126 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 127 | pub struct Max; 128 | 129 | macro_rules! impl_operation_infix { 130 | ($op:ty, $ty:ty, $combineop:tt, $doc:expr) => { 131 | impl Operation<$ty> for $op { 132 | #[doc = $doc] 133 | #[inline] 134 | fn combine(&self, a: &$ty, b: &$ty) -> $ty { 135 | *a $combineop *b 136 | } 137 | } 138 | } 139 | } 140 | macro_rules! impl_operation_prefix { 141 | ($op:ty, $ty:ty, $combinef:expr, $doc:expr) => { 142 | impl Operation<$ty> for $op { 143 | #[doc = $doc] 144 | #[inline] 145 | fn combine(&self, a: &$ty, b: &$ty) -> $ty { 146 | $combinef(*a, *b) 147 | } 148 | } 149 | } 150 | } 151 | macro_rules! impl_identity { 152 | ($op:ty, $ty:ty, $iden:expr, $doc:expr) => { 153 | impl Identity<$ty> for $op { 154 | #[doc = $doc] 155 | #[inline] 156 | fn identity(&self) -> $ty { 157 | $iden 158 | } 159 | } 160 | } 161 | } 162 | macro_rules! impl_inverse { 163 | ($op:ty, $ty:ty, $uncombineop:tt, $doc:expr) => { 164 | impl Invertible<$ty> for $op { 165 | #[doc = $doc] 166 | #[inline] 167 | fn uncombine(&self, a: &mut $ty, b: &$ty) { 168 | *a = *a $uncombineop *b; 169 | } 170 | } 171 | } 172 | } 173 | macro_rules! impl_unsigned_primitive { 174 | ($ty:tt) => { 175 | impl_operation_infix!(Add, $ty, +, "Returns the sum."); 176 | impl_identity!(Add, $ty, 0, "Returns zero."); 177 | impl Commutative<$ty> for Add {} 178 | 179 | impl_operation_infix!(Add, Wrapping<$ty>, +, "Returns the sum."); 180 | impl_identity!(Add, Wrapping<$ty>, Wrapping(0), "Returns zero."); 181 | impl_inverse!(Add, Wrapping<$ty>, -, "Returns the difference."); 182 | impl Commutative> for Add {} 183 | 184 | impl_operation_infix!(Xor, $ty, ^, "Returns the bitwise exclusive or."); 185 | impl_identity!(Xor, $ty, 0, "Returns zero."); 186 | impl_inverse!(Xor, $ty, ^, "Returns the bitwise exclusive or."); 187 | impl Commutative<$ty> for Xor {} 188 | 189 | impl_operation_infix!(Mul, $ty, *, "Returns the product."); 190 | impl_identity!(Mul, $ty, 1, "Returns one."); 191 | impl Commutative<$ty> for Mul {} 192 | 193 | impl_operation_infix!(Mul, Wrapping<$ty>, *, "Returns the product."); 194 | impl_identity!(Mul, Wrapping<$ty>, Wrapping(1), "Returns one."); 195 | impl Commutative> for Mul {} 196 | 197 | impl_operation_infix!(And, $ty, &, "Returns the bitwise and."); 198 | impl_identity!(And, $ty, std::$ty::MAX, "Returns the largest possible value."); 199 | impl Commutative<$ty> for And {} 200 | 201 | impl_operation_infix!(Or, $ty, &, "Returns the bitwise or."); 202 | impl_identity!(Or, $ty, 0, "Returns zero."); 203 | impl Commutative<$ty> for Or {} 204 | 205 | impl_operation_prefix!(Min, $ty, std::cmp::min, "Returns the minimum."); 206 | impl_identity!(Min, $ty, std::$ty::MAX, "Returns the largest possible value."); 207 | impl Commutative<$ty> for Min {} 208 | 209 | impl_operation_prefix!(Max, $ty, std::cmp::max, "Returns the maximum."); 210 | impl_identity!(Max, $ty, 0, "Returns zero."); 211 | impl Commutative<$ty> for Max {} 212 | } 213 | } 214 | impl_unsigned_primitive!(u8); 215 | impl_unsigned_primitive!(u16); 216 | impl_unsigned_primitive!(u32); 217 | impl_unsigned_primitive!(u64); 218 | impl_unsigned_primitive!(u128); 219 | impl_unsigned_primitive!(usize); 220 | 221 | macro_rules! impl_signed_primitive { 222 | ($ty:tt) => { 223 | impl_operation_infix!(Add, $ty, +, "Returns the sum."); 224 | impl_identity!(Add, $ty, 0, "Returns zero."); 225 | impl_inverse!(Add, $ty, -, "Returns the difference."); 226 | impl Commutative<$ty> for Add {} 227 | 228 | impl_operation_infix!(Add, Wrapping<$ty>, +, "Returns the sum."); 229 | impl_identity!(Add, Wrapping<$ty>, Wrapping(0), "Returns zero."); 230 | impl_inverse!(Add, Wrapping<$ty>, -, "Returns the difference."); 231 | impl Commutative> for Add {} 232 | 233 | impl_operation_infix!(Xor, $ty, ^, "Returns the bitwise exclusive or."); 234 | impl_identity!(Xor, $ty, 0, "Returns zero."); 235 | impl_inverse!(Xor, $ty, ^, "Returns the bitwise exclusive or."); 236 | impl Commutative<$ty> for Xor {} 237 | 238 | impl_operation_infix!(Mul, $ty, *, "Returns the product."); 239 | impl_identity!(Mul, $ty, 1, "Returns one."); 240 | impl Commutative<$ty> for Mul {} 241 | 242 | impl_operation_infix!(Mul, Wrapping<$ty>, *, "Returns the product."); 243 | impl_identity!(Mul, Wrapping<$ty>, Wrapping(1), "Returns one."); 244 | impl Commutative> for Mul {} 245 | 246 | impl_operation_infix!(And, $ty, &, "Returns the bitwise and."); 247 | impl_identity!(And, $ty, -1, "Returns negative one."); 248 | impl Commutative<$ty> for And {} 249 | 250 | impl_operation_infix!(Or, $ty, &, "Returns the bitwise or."); 251 | impl_identity!(Or, $ty, 0, "Returns zero."); 252 | impl Commutative<$ty> for Or {} 253 | 254 | impl_operation_prefix!(Min, $ty, std::cmp::min, "Returns the minimum."); 255 | impl_identity!(Min, $ty, std::$ty::MAX, "Returns the largest possible value."); 256 | impl Commutative<$ty> for Min {} 257 | 258 | impl_operation_prefix!(Max, $ty, std::cmp::max, "Returns the maximum."); 259 | impl_identity!(Max, $ty, std::$ty::MIN, "Returns the smallest possible value."); 260 | impl Commutative<$ty> for Max {} 261 | } 262 | } 263 | impl_signed_primitive!(i8); 264 | impl_signed_primitive!(i16); 265 | impl_signed_primitive!(i32); 266 | impl_signed_primitive!(i64); 267 | impl_signed_primitive!(i128); 268 | impl_signed_primitive!(isize); 269 | 270 | impl_operation_infix!(Add, f32, +, "Returns the sum."); 271 | impl_inverse!(Add, f32, -, "Returns the difference."); 272 | impl_identity!(Add, f32, 0.0, "Returns zero."); 273 | impl Commutative for Add {} 274 | 275 | impl_operation_infix!(Mul, f32, *, "Returns the product."); 276 | impl_inverse!(Mul, f32, /, "Returns the ratio."); 277 | impl_identity!(Mul, f32, 1.0, "Returns one."); 278 | impl Commutative for Mul {} 279 | 280 | impl_operation_infix!(Add, f64, +, "Returns the sum."); 281 | impl_inverse!(Add, f64, -, "Returns the difference."); 282 | impl_identity!(Add, f64, 0.0, "Returns zero."); 283 | impl Commutative for Add {} 284 | 285 | impl_operation_infix!(Mul, f64, *, "Returns the product."); 286 | impl_inverse!(Mul, f64, /, "Returns the ratio."); 287 | impl_identity!(Mul, f64, 1.0, "Returns one."); 288 | impl Commutative for Mul {} 289 | 290 | 291 | /// Variant of [`Min`] that considers NaN the largest value. 292 | /// 293 | /// [`Min`]: struct.Min.html 294 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 295 | pub struct MinIgnoreNaN; 296 | impl_identity!(MinIgnoreNaN, f32, std::f32::NAN, "Returns NaN."); 297 | impl_identity!(MinIgnoreNaN, f64, std::f64::NAN, "Returns NaN."); 298 | impl Commutative for MinIgnoreNaN {} 299 | impl Commutative for MinIgnoreNaN {} 300 | impl Operation for MinIgnoreNaN { 301 | /// Returns the smallest of the two values. 302 | /// 303 | /// If either argument is NaN, the other is returned. 304 | fn combine(&self, a: &f32, b: &f32) -> f32 { 305 | if b > a || b.is_nan() { *a } else { *b } 306 | } 307 | } 308 | impl Operation for MinIgnoreNaN { 309 | /// Returns the smallest of the two values. 310 | /// 311 | /// If either argument is NaN, the other is returned. 312 | fn combine(&self, a: &f64, b: &f64) -> f64 { 313 | if b > a || b.is_nan() { *a } else { *b } 314 | } 315 | } 316 | 317 | /// Variant of [`Min`] that considers NaN the smallest value. 318 | /// 319 | /// [`Min`]: struct.Min.html 320 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 321 | pub struct MinTakeNaN; 322 | impl_identity!(MinTakeNaN, f32, std::f32::INFINITY, "Returns infinity."); 323 | impl_identity!(MinTakeNaN, f64, std::f64::INFINITY, "Returns infinity."); 324 | impl Commutative for MinTakeNaN {} 325 | impl Commutative for MinTakeNaN {} 326 | impl Operation for MinTakeNaN { 327 | /// Returns the smallest of the two values. 328 | /// 329 | /// If either argument is NaN, this method returns NaN. 330 | fn combine(&self, a: &f32, b: &f32) -> f32 { 331 | if b > a || a.is_nan() { *a } else { *b } 332 | } 333 | } 334 | impl Operation for MinTakeNaN { 335 | /// Returns the smallest of the two values. 336 | /// 337 | /// If either argument is NaN, this method returns NaN. 338 | fn combine(&self, a: &f64, b: &f64) -> f64 { 339 | if b > a || a.is_nan() { *a } else { *b } 340 | } 341 | } 342 | 343 | /// Variant of [`Max`] that considers NaN the smallest value. 344 | /// 345 | /// [`Max`]: struct.Max.html 346 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 347 | pub struct MaxIgnoreNaN; 348 | impl_identity!(MaxIgnoreNaN, f32, std::f32::NAN, "Returns NaN."); 349 | impl_identity!(MaxIgnoreNaN, f64, std::f64::NAN, "Returns NaN."); 350 | impl Commutative for MaxIgnoreNaN {} 351 | impl Commutative for MaxIgnoreNaN {} 352 | impl Operation for MaxIgnoreNaN { 353 | /// Returns the largest of the two values. 354 | /// 355 | /// If either argument is NaN, the other is returned. 356 | fn combine(&self, a: &f32, b: &f32) -> f32 { 357 | if b < a || b.is_nan() { *a } else { *b } 358 | } 359 | } 360 | impl Operation for MaxIgnoreNaN { 361 | /// Returns the largest of the two values. 362 | /// 363 | /// If either argument is NaN, the other is returned. 364 | fn combine(&self, a: &f64, b: &f64) -> f64 { 365 | if b < a || b.is_nan() { *a } else { *b } 366 | } 367 | } 368 | 369 | /// Variant of [`Max`] that considers NaN the largest value. 370 | /// 371 | /// [`Max`]: struct.Max.html 372 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 373 | pub struct MaxTakeNaN; 374 | impl_identity!(MaxTakeNaN, f32, std::f32::NEG_INFINITY, "Returns negative infinity."); 375 | impl_identity!(MaxTakeNaN, f64, std::f64::NEG_INFINITY, "Returns negative infinity."); 376 | impl Commutative for MaxTakeNaN {} 377 | impl Commutative for MaxTakeNaN {} 378 | impl Operation for MaxTakeNaN { 379 | /// Returns the largest of the two values. 380 | /// 381 | /// If either argument is NaN, this method returns NaN. 382 | fn combine(&self, a: &f32, b: &f32) -> f32 { 383 | if b < a || a.is_nan() { *a } else { *b } 384 | } 385 | } 386 | impl Operation for MaxTakeNaN { 387 | /// Returns the largest of the two values. 388 | /// 389 | /// If either argument is NaN, this method returns NaN. 390 | fn combine(&self, a: &f64, b: &f64) -> f64 { 391 | if b < a || a.is_nan() { *a } else { *b } 392 | } 393 | } 394 | 395 | impl_operation_infix!(And, bool, &&, "Returns the boolean and."); 396 | impl_identity!(And, bool, true, "Returns `true`."); 397 | 398 | impl_operation_infix!(Or, bool, ||, "Returns the boolean or."); 399 | impl_identity!(Or, bool, false, "Returns `false`."); 400 | 401 | impl_operation_infix!(Xor, bool, ^, "Returns the boolean xor."); 402 | impl_inverse!(Xor, bool, ^, "Returns the boolean xor."); 403 | impl_identity!(Xor, bool, false, "Returns `false`."); 404 | 405 | #[cfg(test)] 406 | mod tests { 407 | use std::{f32, i32, u32}; 408 | use crate::ops::*; 409 | #[test] 410 | fn ops_nan() { 411 | assert_eq!(MaxIgnoreNaN.combine_both(0.0, 1.0), 1.0); 412 | assert_eq!(MaxIgnoreNaN.combine_both(1.0, 0.0), 1.0); 413 | assert_eq!(MaxIgnoreNaN.combine_both(f32::NAN, 1.0), 1.0); 414 | assert_eq!(MaxIgnoreNaN.combine_both(1.0, f32::NAN), 1.0); 415 | assert_eq!(MaxIgnoreNaN.combine_both(f32::NAN, f32::NEG_INFINITY), 416 | f32::NEG_INFINITY); 417 | assert_eq!(MaxIgnoreNaN.combine_both(f32::NEG_INFINITY, f32::NAN), 418 | f32::NEG_INFINITY); 419 | assert!(MaxIgnoreNaN.combine_both(f32::NAN, f32::NAN).is_nan()); 420 | 421 | assert_eq!(MinIgnoreNaN.combine_both(0.0, 1.0), 0.0); 422 | assert_eq!(MinIgnoreNaN.combine_both(1.0, 0.0), 0.0); 423 | assert_eq!(MinIgnoreNaN.combine_both(f32::NAN, 1.0), 1.0); 424 | assert_eq!(MinIgnoreNaN.combine_both(1.0, f32::NAN), 1.0); 425 | assert_eq!(MinIgnoreNaN.combine_both(f32::NAN, f32::INFINITY), f32::INFINITY); 426 | assert_eq!(MinIgnoreNaN.combine_both(f32::INFINITY, f32::NAN), f32::INFINITY); 427 | assert!(MinIgnoreNaN.combine_both(f32::NAN, f32::NAN).is_nan()); 428 | 429 | assert_eq!(MaxTakeNaN.combine_both(0.0, 1.0), 1.0); 430 | assert_eq!(MaxTakeNaN.combine_both(1.0, 0.0), 1.0); 431 | assert!(MaxTakeNaN.combine_both(f32::NAN, f32::INFINITY).is_nan()); 432 | assert!(MaxTakeNaN.combine_both(f32::INFINITY, f32::NAN).is_nan()); 433 | assert!(MaxTakeNaN.combine_both(f32::NAN, f32::NEG_INFINITY).is_nan()); 434 | assert!(MaxTakeNaN.combine_both(f32::NEG_INFINITY, f32::NAN).is_nan()); 435 | assert!(MaxTakeNaN.combine_both(f32::NAN, f32::NAN).is_nan()); 436 | 437 | assert_eq!(MinTakeNaN.combine_both(0.0, 1.0), 0.0); 438 | assert_eq!(MinTakeNaN.combine_both(1.0, 0.0), 0.0); 439 | assert!(MinTakeNaN.combine_both(f32::NAN, f32::INFINITY).is_nan()); 440 | assert!(MinTakeNaN.combine_both(f32::INFINITY, f32::NAN).is_nan()); 441 | assert!(MinTakeNaN.combine_both(f32::NAN, f32::NEG_INFINITY).is_nan()); 442 | assert!(MinTakeNaN.combine_both(f32::NEG_INFINITY, f32::NAN).is_nan()); 443 | assert!(MinTakeNaN.combine_both(f32::NAN, f32::NAN).is_nan()); 444 | } 445 | #[test] 446 | fn ops_and_identity() { 447 | for i in -200i32 ..= 200i32 { 448 | assert_eq!(And.combine_both(i, And.identity()), i); 449 | } 450 | assert_eq!(And.combine_both(i32::MAX, And.identity()), i32::MAX); 451 | assert_eq!(And.combine_both(i32::MIN, And.identity()), i32::MIN); 452 | assert_eq!(And.combine_both(0i32, And.identity()), 0i32); 453 | 454 | assert_eq!(And.combine_both(0u32, And.identity()), 0u32); 455 | assert_eq!(And.combine_both(u32::MAX, And.identity()), u32::MAX); 456 | } 457 | } 458 | 459 | /// Store several pieces of information in each node. 460 | #[derive(Clone,Copy,Eq,PartialEq,Ord,PartialOrd,Debug,Default,Hash)] 461 | pub struct Pair { 462 | a: A, b: B 463 | } 464 | impl Pair { 465 | /// Create a pair operation. 466 | pub fn wrap(a: A, b: B) -> Pair { 467 | Pair { a: a, b: b } 468 | } 469 | /// Returns the inner operations. 470 | pub fn into_inner(self) -> (A, B) { 471 | (self.a, self.b) 472 | } 473 | } 474 | impl, B: Operation> Operation<(TA, TB)> for Pair { 475 | #[inline] 476 | fn combine(&self, a: &(TA, TB), b: &(TA, TB)) -> (TA, TB) { 477 | (self.a.combine(&a.0, &b.0), self.b.combine(&a.1, &b.1)) 478 | } 479 | #[inline] 480 | fn combine_mut(&self, a: &mut (TA, TB), b: &(TA, TB)) { 481 | self.a.combine_mut(&mut a.0, &b.0); 482 | self.b.combine_mut(&mut a.1, &b.1); 483 | } 484 | #[inline] 485 | fn combine_mut2(&self, a: &(TA, TB), b: &mut (TA, TB)) { 486 | self.a.combine_mut2(&a.0, &mut b.0); 487 | self.b.combine_mut2(&a.1, &mut b.1); 488 | } 489 | #[inline] 490 | fn combine_left(&self, a: (TA, TB), b: &(TA, TB)) -> (TA, TB) { 491 | (self.a.combine_left(a.0, &b.0), self.b.combine_left(a.1, &b.1)) 492 | } 493 | #[inline] 494 | fn combine_right(&self, a: &(TA, TB), b: (TA, TB)) -> (TA, TB) { 495 | (self.a.combine_right(&a.0, b.0), self.b.combine_right(&a.1, b.1)) 496 | } 497 | #[inline] 498 | fn combine_both(&self, a: (TA, TB), b: (TA, TB)) -> (TA, TB) { 499 | (self.a.combine_both(a.0, b.0), self.b.combine_both(a.1, b.1)) 500 | } 501 | } 502 | impl, B: Invertible> Invertible<(TA, TB)> for Pair { 503 | #[inline(always)] 504 | fn uncombine(&self, a: &mut (TA, TB), b: &(TA, TB)) { 505 | self.a.uncombine(&mut a.0, &b.0); 506 | self.b.uncombine(&mut a.1, &b.1); 507 | } 508 | } 509 | impl, B: Commutative> Commutative<(TA, TB)> for Pair {} 510 | impl, B: Identity> Identity<(TA,TB)> for Pair { 511 | fn identity(&self) -> (TA, TB) { 512 | (self.a.identity(), self.b.identity()) 513 | } 514 | } 515 | -------------------------------------------------------------------------------- /src/ops/num.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "num-bigint")] 2 | mod bigint { 3 | 4 | use crate::ops::{Operation, Commutative, Identity, Invertible}; 5 | use crate::ops::{Add, Mul}; 6 | use num_bigint::{BigInt, BigUint}; 7 | 8 | impl Operation for Add { 9 | /// Returns the sum. This usually allocates memory. 10 | fn combine(&self, a: &BigInt, b: &BigInt) -> BigInt { 11 | a + b 12 | } 13 | /// Computes the sum while reusing memory in `a`. 14 | fn combine_mut(&self, a: &mut BigInt, b: &BigInt) { 15 | *a += b; 16 | } 17 | /// Computes the sum while reusing memory in `b`. 18 | fn combine_mut2(&self, a: &BigInt, b: &mut BigInt) { 19 | *b += a; 20 | } 21 | /// Computes the sum while reusing memory from `a`. 22 | fn combine_left(&self, a: BigInt, b: &BigInt) -> BigInt { 23 | a + b 24 | } 25 | /// Computes the sum while reusing memory from `b`. 26 | fn combine_right(&self, a: &BigInt, b: BigInt) -> BigInt { 27 | a + b 28 | } 29 | /// Computes the sum while reusing memory from the larger of `a` and `b`. 30 | fn combine_both(&self, a: BigInt, b: BigInt) -> BigInt { 31 | a + b 32 | } 33 | } 34 | impl Commutative for Add {} 35 | impl Identity for Add { 36 | /// Returns zero. 37 | fn identity(&self) -> BigInt { 38 | 0.into() 39 | } 40 | } 41 | impl Invertible for Add { 42 | /// Computes the difference, while reusing memory in `a`. 43 | fn uncombine(&self, a: &mut BigInt, b: &BigInt) { 44 | *a -= b; 45 | } 46 | } 47 | 48 | impl Operation for Add { 49 | /// Returns the sum. This usually allocates memory. 50 | fn combine(&self, a: &BigUint, b: &BigUint) -> BigUint { 51 | a + b 52 | } 53 | /// Computes the sum while reusing memory in `a`. 54 | fn combine_mut(&self, a: &mut BigUint, b: &BigUint) { 55 | *a += b; 56 | } 57 | /// Computes the sum while reusing memory in `b`. 58 | fn combine_mut2(&self, a: &BigUint, b: &mut BigUint) { 59 | *b += a; 60 | } 61 | /// Computes the sum while reusing memory from `a`. 62 | fn combine_left(&self, a: BigUint, b: &BigUint) -> BigUint { 63 | a + b 64 | } 65 | /// Computes the sum while reusing memory from `b`. 66 | fn combine_right(&self, a: &BigUint, b: BigUint) -> BigUint { 67 | a + b 68 | } 69 | /// Computes the sum while reusing memory from the larger of `a` and `b`. 70 | fn combine_both(&self, a: BigUint, b: BigUint) -> BigUint { 71 | a + b 72 | } 73 | } 74 | impl Commutative for Add {} 75 | impl Identity for Add { 76 | /// Returns zero. 77 | fn identity(&self) -> BigUint { 78 | 0u32.into() 79 | } 80 | } 81 | 82 | 83 | impl Operation for Mul { 84 | /// Returns the product. This usually allocates memory. 85 | fn combine(&self, a: &BigInt, b: &BigInt) -> BigInt { 86 | a * b 87 | } 88 | /// Computes the product while reusing memory in `a`. 89 | fn combine_mut(&self, a: &mut BigInt, b: &BigInt) { 90 | *a *= b; 91 | } 92 | /// Computes the product while reusing memory in `b`. 93 | fn combine_mut2(&self, a: &BigInt, b: &mut BigInt) { 94 | *b *= a; 95 | } 96 | /// Computes the product while reusing memory from `a`. 97 | fn combine_left(&self, a: BigInt, b: &BigInt) -> BigInt { 98 | a * b 99 | } 100 | /// Computes the product while reusing memory from `b`. 101 | fn combine_right(&self, a: &BigInt, b: BigInt) -> BigInt { 102 | a * b 103 | } 104 | /// Computes the product while reusing memory from the larger of `a` and `b`. 105 | fn combine_both(&self, a: BigInt, b: BigInt) -> BigInt { 106 | a * b 107 | } 108 | } 109 | impl Commutative for Mul {} 110 | impl Identity for Mul { 111 | /// Returns one. 112 | fn identity(&self) -> BigInt { 113 | 1.into() 114 | } 115 | } 116 | 117 | impl Operation for Mul { 118 | /// Returns the product. This usually allocates memory. 119 | fn combine(&self, a: &BigUint, b: &BigUint) -> BigUint { 120 | a * b 121 | } 122 | /// Computes the product while reusing memory in `a`. 123 | fn combine_mut(&self, a: &mut BigUint, b: &BigUint) { 124 | *a *= b; 125 | } 126 | /// Computes the product while reusing memory in `b`. 127 | fn combine_mut2(&self, a: &BigUint, b: &mut BigUint) { 128 | *b *= a; 129 | } 130 | /// Computes the product while reusing memory from `a`. 131 | fn combine_left(&self, a: BigUint, b: &BigUint) -> BigUint { 132 | a * b 133 | } 134 | /// Computes the product while reusing memory from `b`. 135 | fn combine_right(&self, a: &BigUint, b: BigUint) -> BigUint { 136 | a * b 137 | } 138 | /// Computes the product while reusing memory from the larger of `a` and `b`. 139 | fn combine_both(&self, a: BigUint, b: BigUint) -> BigUint { 140 | a * b 141 | } 142 | } 143 | impl Commutative for Mul {} 144 | impl Identity for Mul { 145 | /// Returns zero. 146 | fn identity(&self) -> BigUint { 147 | 1u32.into() 148 | } 149 | } 150 | } 151 | 152 | -------------------------------------------------------------------------------- /src/propagating.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | use std::default::Default; 3 | 4 | use crate::ops::{Commutative, Identity}; 5 | 6 | /// This data structure allows range modification and single element queries. 7 | /// 8 | /// This tree allocates `2n * sizeof(N)` bytes of memory. 9 | /// 10 | /// This tree is implemented using a binary tree, where each node contains the changes 11 | /// that need to be propogated to its children. 12 | /// 13 | /// # Examples 14 | /// 15 | /// Quickly add something to every value in some interval. 16 | /// 17 | /// ```rust 18 | /// use segment_tree::PointSegment; 19 | /// use segment_tree::ops::Add; 20 | /// 21 | /// use std::iter::repeat; 22 | /// 23 | /// // make a giant tree of zeroes 24 | /// let mut tree = PointSegment::build(repeat(0).take(1_000_000).collect(), Add); 25 | /// 26 | /// // add one to every value between 200 and 500000 27 | /// tree.modify(200, 500_000, 1); 28 | /// assert_eq!(tree.query(100), 0); 29 | /// assert_eq!(tree.query(200), 1); 30 | /// assert_eq!(tree.query(500), 1); 31 | /// assert_eq!(tree.query(499_999), 1); 32 | /// assert_eq!(tree.query(500_000), 0); 33 | /// 34 | /// // add five to every value between 0 and 1000 35 | /// tree.modify(0, 1000, 5); 36 | /// assert_eq!(tree.query(10), 5); 37 | /// assert_eq!(tree.query(500), 6); 38 | /// assert_eq!(tree.query(10_000), 1); 39 | /// assert_eq!(tree.query(600_000), 0); 40 | /// ``` 41 | pub struct PointSegment where O: Commutative + Identity { 42 | buf: Vec, 43 | n: usize, 44 | op: O 45 | } 46 | 47 | impl + Identity> PointSegment { 48 | /// Builds a tree using the given buffer. If the given buffer is less than half full, 49 | /// this function allocates. 50 | /// Uses `O(len)` time. 51 | pub fn build(mut buf: Vec, op: O) -> PointSegment { 52 | let n = buf.len(); 53 | buf.reserve_exact(n); 54 | for i in 0..n { 55 | let val = mem::replace(&mut buf[i], op.identity()); 56 | buf.push(val); 57 | } 58 | PointSegment { buf: buf, n: n, op: op } 59 | } 60 | /// Allocate a new buffer and build the tree using the values in the slice. 61 | /// Uses `O(len)` time. 62 | pub fn build_slice(buf: &[N], op: O) -> PointSegment where N: Clone { 63 | PointSegment::build_iter(buf.iter().cloned(), op) 64 | } 65 | /// Allocate a new buffer and build the tree using the values in the iterator. 66 | /// Uses `O(len)` time. 67 | pub fn build_iter>(iter: I, op: O) -> PointSegment { 68 | let n = iter.len(); 69 | let mut buf = Vec::with_capacity(2*n); 70 | for _ in 0..n { buf.push(op.identity()); } 71 | buf.extend(iter); 72 | PointSegment { 73 | buf: buf, 74 | n: n, op: op 75 | } 76 | } 77 | /// Computes the value at `p`. 78 | /// Uses `O(log(len))` time. 79 | pub fn query(&self, mut p: usize) -> N { 80 | p += self.n; 81 | let mut res = self.op.identity(); 82 | while p > 0 { 83 | res = self.op.combine_left(res, &self.buf[p]); 84 | p >>= 1; 85 | } 86 | res 87 | } 88 | /// Combine every value in the interval with `delta`. 89 | /// Uses `O(log(len))` time. 90 | pub fn modify(&mut self, mut l: usize, mut r: usize, delta: N) { 91 | l += self.n; r += self.n; 92 | while l < r { 93 | if l&1 == 1 { 94 | self.op.combine_mut(&mut self.buf[l], &delta); 95 | l += 1; 96 | } 97 | if r&1 == 1 { 98 | r -= 1; 99 | self.op.combine_mut(&mut self.buf[r], &delta); 100 | } 101 | l >>= 1; r >>= 1; 102 | } 103 | } 104 | /// Propogate all changes to the leaves in the tree and return a mutable slice 105 | /// containing the leaves. 106 | /// 107 | /// Uses `O(len)` time. 108 | pub fn propogate(&mut self) -> &mut [N] { 109 | for i in 1..self.n { 110 | let prev = mem::replace(&mut self.buf[i], self.op.identity()); 111 | self.op.combine_mut(&mut self.buf[i<<1], &prev); 112 | self.op.combine_mut(&mut self.buf[i<<1|1], &prev); 113 | } 114 | &mut self.buf[self.n..] 115 | } 116 | /// Returns the number of values in the underlying array. 117 | /// Uses `O(1)` time. 118 | #[inline(always)] 119 | pub fn len(&self) -> usize { 120 | self.n 121 | } 122 | } 123 | 124 | impl + Commutative + Clone> Clone for PointSegment { 125 | #[inline] 126 | fn clone(&self) -> PointSegment { 127 | PointSegment { 128 | buf: self.buf.clone(), n: self.n, op: self.op.clone() 129 | } 130 | } 131 | } 132 | impl + Commutative + Default> Default for PointSegment { 133 | #[inline] 134 | fn default() -> PointSegment { 135 | PointSegment { buf: Vec::new(), n: 0, op: Default::default() } 136 | } 137 | } 138 | 139 | #[cfg(test)] 140 | mod tests { 141 | use crate::propagating::*; 142 | use crate::ops::*; 143 | use rand::prelude::*; 144 | use rand::distributions::Standard; 145 | use std::num::Wrapping; 146 | 147 | #[test] 148 | fn test() { 149 | let mut rng = thread_rng(); 150 | for i in 1..130 { 151 | let mut buf: Vec> = rng.sample_iter(&Standard) 152 | .map(|n| Wrapping(n)).take(i).collect(); 153 | let mut tree = match i%3 { 154 | 0 => PointSegment::build_slice(&buf[..], Add), 155 | 1 => PointSegment::build_iter(buf.iter().cloned(), Add), 156 | 2 => PointSegment::build(buf.clone(), Add), 157 | _ => unreachable!() 158 | }; 159 | let tests: Vec<(usize, usize, i32)> = rng.sample_iter(&Standard) 160 | .take(10).collect(); 161 | for (n, m, v) in tests { 162 | let n = n % i; 163 | let m = m % i; 164 | if n > m { continue; } 165 | for index in n..m { buf[index] += Wrapping(v); } 166 | tree.modify(n, m, Wrapping(v)); 167 | for index in 0..i { 168 | assert_eq!(buf[index], tree.query(index)); 169 | } 170 | } 171 | assert_eq!(&mut buf[..], tree.propogate()); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/segment_tree.rs: -------------------------------------------------------------------------------- 1 | use std::{mem, fmt}; 2 | use std::cmp::{PartialEq, Eq}; 3 | use std::default::Default; 4 | use std::hash::{Hash, Hasher}; 5 | 6 | use crate::ops::{Operation, Commutative, Identity}; 7 | use crate::maybe_owned::MaybeOwned; 8 | 9 | /// This data structure allows range queries and single element modification. 10 | /// 11 | /// This tree allocates `2n * sizeof(N)` bytes of memory. 12 | /// 13 | /// This tree is implemented using a segment tree. A segment tree is a binary tree where 14 | /// each node contains the combination of the children under the operation. 15 | /// 16 | ///# Examples 17 | /// 18 | /// This example solves the [range minimum query][1] problem. 19 | /// 20 | /// ```rust 21 | /// use segment_tree::SegmentPoint; 22 | /// use segment_tree::ops::Min; 23 | /// 24 | /// // Let's solve the range minimum query on this array. 25 | /// let mut tree = SegmentPoint::build( 26 | /// vec![10i32, 5, 6, 4, 12, 8, 9, 3, 2, 1, 5], Min 27 | /// ); // 0 1 2 3 4 5 6 7 8 9 10 - indices 28 | /// 29 | /// // Find the minimum value in a few intervals. Note that the second argument is 30 | /// // exclusive. 31 | /// assert_eq!(tree.query(0, 2), 5); 32 | /// assert_eq!(tree.query(4, 8), 3); 33 | /// assert_eq!(tree.query(3, 11), 1); 34 | /// assert_eq!(tree.query(0, 11), 1); 35 | /// 36 | /// // query returns the identity if given an invalid interval 37 | /// // The identity of min is the MAX. 38 | /// assert_eq!(tree.query(4, 2), std::i32::MAX); 39 | /// 40 | /// // We can change individual values in the array as well. 41 | /// tree.modify(2, 0); 42 | /// assert_eq!(tree.query(0, 3), 0); 43 | /// assert_eq!(tree.query(3, 6), 4); 44 | /// 45 | /// // We can view the values currently stored at any time. 46 | /// assert_eq!(tree.view(), &[10, 5, 0, 4, 12, 8, 9, 3, 2, 1, 5]); 47 | /// ``` 48 | /// 49 | /// We can also use a `SegmentPoint` to find the sum of any interval, by changing the 50 | /// operator to [`Add`]. 51 | /// 52 | /// ```rust 53 | /// use segment_tree::SegmentPoint; 54 | /// use segment_tree::ops::Add; 55 | /// 56 | /// let mut tree = SegmentPoint::build( 57 | /// vec![10, 5, 6, 4, 12, 8, 9, 3, 2, 1, 5], Add 58 | /// ); // 0 1 2 3 4 5 6 7 8 9 10 - indices 59 | /// 60 | /// assert_eq!(tree.query(4, 8), 12 + 8 + 9 + 3); 61 | /// assert_eq!(tree.query(1, 3), 5 + 6); 62 | /// 63 | /// // we can still modify values in the tree 64 | /// tree.modify(2, 4); 65 | /// assert_eq!(tree.query(1, 3), 5 + 4); 66 | /// assert_eq!(tree.query(4, 8), 12 + 8 + 9 + 3); 67 | /// 68 | /// assert_eq!(tree.view(), &[10, 5, 4, 4, 12, 8, 9, 3, 2, 1, 5]); 69 | /// ``` 70 | /// 71 | /// [1]: https://en.wikipedia.org/wiki/Range_minimum_query 72 | /// [`Add`]: ops/struct.Add.html 73 | pub struct SegmentPoint where O: Operation { 74 | buf: Vec, 75 | n: usize, 76 | op: O 77 | } 78 | 79 | impl> SegmentPoint { 80 | /// Builds a tree using the given buffer. If the given buffer is less than half full, 81 | /// this function allocates. This function clones every value in the input array. 82 | /// Uses `O(len)` time. 83 | /// 84 | /// See also the function [`build_noalloc`]. 85 | /// 86 | /// [`build_noalloc`]: struct.SegmentPoint.html#method.build_noalloc 87 | pub fn build(mut buf: Vec, op: O) -> SegmentPoint where N: Clone { 88 | let n = buf.len(); 89 | buf.reserve_exact(n); 90 | for i in 0..n { 91 | debug_assert!(i < buf.len()); 92 | let clone = unsafe { buf.get_unchecked(i).clone() }; // i < n < buf.len() 93 | buf.push(clone); 94 | } 95 | SegmentPoint::build_noalloc(buf, op) 96 | } 97 | /// Set the value at the specified index and return the old value. 98 | /// Uses `O(log(len))` time. 99 | pub fn modify(&mut self, mut p: usize, value: N) -> N { 100 | p += self.n; 101 | let res = mem::replace(&mut self.buf[p], value); 102 | while { p >>= 1; p > 0 } { 103 | self.buf[p] = self.op.combine(&self.buf[p<<1], &self.buf[p<<1|1]); 104 | } 105 | res 106 | } 107 | /// Computes `a[l] * a[l+1] * ... * a[r-1]`. 108 | /// Uses `O(log(len))` time. 109 | /// 110 | /// If `l >= r`, this method returns the identity. 111 | /// 112 | /// See [`query_noiden`] or [`query_noclone`] for a version that works with 113 | /// non-[commutative operations][1]. 114 | /// 115 | /// [`query_noiden`]: struct.SegmentPoint.html#method.query_noiden 116 | /// [`query_noclone`]: struct.SegmentPoint.html#method.query_noclone 117 | /// [1]: ops/trait.Commutative.html 118 | pub fn query(&self, mut l: usize, mut r: usize) -> N 119 | where 120 | O: Commutative + Identity 121 | { 122 | let mut res = self.op.identity(); 123 | l += self.n; r += self.n; 124 | while l < r { 125 | if l&1 == 1 { 126 | res = self.op.combine_left(res, &self.buf[l]); 127 | l += 1; 128 | } 129 | if r&1 == 1 { 130 | r -= 1; 131 | res = self.op.combine_left(res, &self.buf[r]); 132 | } 133 | l >>= 1; r >>= 1; 134 | } 135 | res 136 | } 137 | /// Combine the value at `p` with `delta`. 138 | /// Uses `O(log(len))` time. 139 | #[inline(always)] 140 | pub fn compose(&mut self, p: usize, delta: &N) 141 | where 142 | O: Commutative 143 | { 144 | self.compose_right(p, delta); 145 | } 146 | /// Combine the value at `p` with `delta`, such that `delta` is the left argument. 147 | /// Uses `O(log(len))` time. 148 | pub fn compose_left(&mut self, mut p: usize, delta: &N) { 149 | p += self.n; 150 | self.op.combine_mut2(delta, &mut self.buf[p]); 151 | while { p >>= 1; p > 0 } { 152 | self.buf[p] = self.op.combine(&self.buf[p<<1], &self.buf[p<<1|1]); 153 | } 154 | } 155 | /// Combine the value at `p` with `delta`, such that `delta` is the right argument. 156 | /// Uses `O(log(len))` time. 157 | pub fn compose_right(&mut self, mut p: usize, delta: &N) { 158 | p += self.n; 159 | self.op.combine_mut(&mut self.buf[p], delta); 160 | while { p >>= 1; p > 0 } { 161 | self.buf[p] = self.op.combine(&self.buf[p<<1], &self.buf[p<<1|1]); 162 | } 163 | } 164 | /// View the values in this segment tree using a slice. Uses `O(1)` time. 165 | #[inline(always)] 166 | pub fn view(&self) -> &[N] { 167 | &self.buf[self.n..] 168 | } 169 | /// The number of elements stored in this segment tree. Uses `O(1)` time. 170 | #[inline(always)] 171 | pub fn len(&self) -> usize { 172 | self.n 173 | } 174 | /// Builds a tree using the given buffer. The buffer must be even in size. 175 | /// The first `n` values have no effect on the resulting tree, 176 | /// and the remaining `n` values contains the array to build the tree on. 177 | /// Uses `O(len)` time. 178 | /// 179 | /// This function panics if the size of the buffer is odd. 180 | /// 181 | /// # Example 182 | /// 183 | /// ```rust 184 | /// use segment_tree::SegmentPoint; 185 | /// use segment_tree::ops::Min; 186 | /// 187 | /// // make a segment point using the other build method 188 | /// let mut tree = SegmentPoint::build( 189 | /// vec![1, 2, 3, 4], Min 190 | /// ); 191 | /// // make a segment point using the build_noalloc method: 192 | /// let mut tree1 = SegmentPoint::build_noalloc( 193 | /// // the first half of the values are ignored 194 | /// vec![3282, 210, 0, 245, 1, 2, 3, 4], Min 195 | /// ); 196 | /// assert_eq!(tree, tree1); 197 | /// 198 | /// let mut tree2 = SegmentPoint::build_noalloc( 199 | /// // we can also try some other first few values 200 | /// vec![0, 0, 0, 0, 1, 2, 3, 4], Min 201 | /// ); 202 | /// assert_eq!(tree1, tree2); 203 | /// assert_eq!(tree, tree2); 204 | /// ``` 205 | pub fn build_noalloc(mut buf: Vec, op: O) -> SegmentPoint { 206 | let len = buf.len(); 207 | let n = len >> 1; 208 | if len & 1 == 1 { 209 | panic!("SegmentPoint::build_noalloc: odd size"); 210 | } 211 | for i in (1..n).rev() { 212 | let res = op.combine(&buf[i<<1], &buf[i<<1 | 1]); 213 | buf[i] = res; 214 | } 215 | SegmentPoint { 216 | buf: buf, op: op, n: n 217 | } 218 | } 219 | } 220 | impl> SegmentPoint { 221 | /// Like [`query`], except it doesn't require the operation to be commutative, nor to 222 | /// have any identity. 223 | /// 224 | /// Computes `a[l] * a[l+1] * ... * a[r-1]`. 225 | /// 226 | /// This method panics if `l >= r`. 227 | /// 228 | /// This method clones at most twice and runs in `O(log(len))` time. 229 | /// See [`query_noclone`] for a version that doesn't clone. 230 | /// 231 | /// [`query_noclone`]: struct.SegmentPoint.html#method.query_noclone 232 | /// [`query`]: struct.SegmentPoint.html#method.query 233 | pub fn query_noiden(&self, mut l: usize, mut r: usize) -> N where N: Clone { 234 | let mut resl = None; 235 | let mut resr = None; 236 | l += self.n; r += self.n; 237 | while l < r { 238 | if l&1 == 1 { 239 | resl = match resl { 240 | None => Some(self.buf[l].clone()), 241 | Some(v) => Some(self.op.combine_left(v, &self.buf[l])) 242 | }; 243 | l += 1; 244 | } 245 | if r&1 == 1 { 246 | r -= 1; 247 | resr = match resr { 248 | None => Some(self.buf[r].clone()), 249 | Some(v) => Some(self.op.combine_right(&self.buf[r], v)) 250 | } 251 | } 252 | l >>= 1; r >>= 1; 253 | } 254 | match resl { 255 | None => match resr { 256 | None => panic!("Empty interval."), 257 | Some(r) => r, 258 | }, 259 | Some(l) => match resr { 260 | None => l, 261 | Some(r) => self.op.combine_both(l, r) 262 | } 263 | } 264 | } 265 | /// Like [`query_noiden`], except it doesn't clone. 266 | /// 267 | /// Computes `a[l] * a[l+1] * ... * a[r-1]`. 268 | /// 269 | /// This method panics if `l >= r`. 270 | /// 271 | /// Uses `O(log(len))` time. 272 | /// See also [`query`] and [`query_commut`]. 273 | /// 274 | /// [`query_commut`]: struct.SegmentPoint.html#method.query_commut 275 | /// [`query_noiden`]: struct.SegmentPoint.html#method.query_noiden 276 | /// [`query`]: struct.SegmentPoint.html#method.query 277 | pub fn query_noclone<'a>(&'a self, mut l: usize, mut r: usize) -> MaybeOwned<'a, N> { 278 | let mut resl = None; 279 | let mut resr = None; 280 | l += self.n; r += self.n; 281 | while l < r { 282 | if l&1 == 1 { 283 | resl = match resl { 284 | None => Some(MaybeOwned::Borrowed(&self.buf[l])), 285 | Some(MaybeOwned::Borrowed(ref v)) => 286 | Some(MaybeOwned::Owned(self.op.combine(v, &self.buf[l]))), 287 | Some(MaybeOwned::Owned(v)) => 288 | Some(MaybeOwned::Owned(self.op.combine_left(v, &self.buf[l]))), 289 | }; 290 | l += 1; 291 | } 292 | if r&1 == 1 { 293 | r -= 1; 294 | resr = match resr { 295 | None => Some(MaybeOwned::Borrowed(&self.buf[r])), 296 | Some(MaybeOwned::Borrowed(ref v)) => 297 | Some(MaybeOwned::Owned(self.op.combine(&self.buf[r], v))), 298 | Some(MaybeOwned::Owned(v)) => 299 | Some(MaybeOwned::Owned(self.op.combine_right(&self.buf[r], v))), 300 | } 301 | } 302 | l >>= 1; r >>= 1; 303 | } 304 | match resl { 305 | None => match resr { 306 | None => panic!("Empty interval."), 307 | Some(v) => v, 308 | }, 309 | Some(MaybeOwned::Borrowed(ref l)) => match resr { 310 | None => MaybeOwned::Borrowed(l), 311 | Some(MaybeOwned::Borrowed(ref r)) => 312 | MaybeOwned::Owned(self.op.combine(l, r)), 313 | Some(MaybeOwned::Owned(r)) => 314 | MaybeOwned::Owned(self.op.combine_right(l, r)) 315 | }, 316 | Some(MaybeOwned::Owned(l)) => match resr { 317 | None => MaybeOwned::Owned(l), 318 | Some(MaybeOwned::Borrowed(ref r)) => 319 | MaybeOwned::Owned(self.op.combine_left(l, r)), 320 | Some(MaybeOwned::Owned(r)) => 321 | MaybeOwned::Owned(self.op.combine_both(l, r)) 322 | } 323 | } 324 | } 325 | } 326 | 327 | impl + Clone> Clone for SegmentPoint { 328 | #[inline] 329 | fn clone(&self) -> SegmentPoint { 330 | SegmentPoint { 331 | buf: self.buf.clone(), n: self.n, op: self.op.clone() 332 | } 333 | } 334 | } 335 | impl> fmt::Debug for SegmentPoint { 336 | #[inline] 337 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 338 | write!(f, "SegmentPoint({:?})", self.view()) 339 | } 340 | } 341 | impl + PartialEq> PartialEq for SegmentPoint { 342 | #[inline] 343 | fn eq(&self, other: &SegmentPoint) -> bool { 344 | self.op.eq(&other.op) && self.view().eq(other.view()) 345 | } 346 | #[inline] 347 | fn ne(&self, other: &SegmentPoint) -> bool { 348 | self.op.ne(&other.op) && self.view().ne(other.view()) 349 | } 350 | } 351 | impl + Eq> Eq for SegmentPoint { } 352 | impl + Default> Default for SegmentPoint { 353 | #[inline] 354 | fn default() -> SegmentPoint { 355 | SegmentPoint { buf: Vec::new(), n: 0, op: Default::default() } 356 | } 357 | } 358 | impl<'a, N: 'a + Hash, O: Operation> Hash for SegmentPoint { 359 | #[inline] 360 | fn hash(&self, state: &mut H) { 361 | self.view().hash(state); 362 | } 363 | } 364 | 365 | #[cfg(test)] 366 | mod tests { 367 | use crate::SegmentPoint; 368 | use crate::ops::*; 369 | use crate::maybe_owned::MaybeOwned; 370 | use rand::prelude::*; 371 | use rand::distributions::{Distribution, Standard}; 372 | use rand::seq::SliceRandom; 373 | use std::num::Wrapping; 374 | 375 | /// Not commutative! Not useful in practice since the root always contains the 376 | /// concatenation of every string. 377 | #[derive(PartialEq, Eq, Clone, Debug)] 378 | struct StrType { 379 | value: String 380 | } 381 | impl StrType { 382 | fn cat(list: &[StrType]) -> StrType { 383 | let mut res = String::new(); 384 | for v in list { 385 | res.push_str(v.value.as_str()); 386 | } 387 | StrType { value: res } 388 | } 389 | fn sub(&self, i: usize, j: usize) -> StrType { 390 | StrType { value: String::from(&self.value[4*i .. 4*j]) } 391 | } 392 | } 393 | impl Distribution for Standard { 394 | fn sample(&self, rng: &mut R) -> StrType { 395 | let a = rng.gen_range('A' as u8, 'Z' as u8+1); 396 | let b = rng.gen_range('A' as u8, 'Z' as u8+1); 397 | let c = rng.gen_range('A' as u8, 'Z' as u8+1); 398 | let d = rng.gen_range('A' as u8, 'Z' as u8+1); 399 | let bytes = [a, b, c, d]; 400 | let utf8 = std::str::from_utf8(&bytes).unwrap(); 401 | StrType { value: String::from(utf8) } 402 | } 403 | } 404 | impl Operation for Add { 405 | fn combine(&self, a: &StrType, b: &StrType) -> StrType { 406 | StrType { 407 | value: a.value.clone() + b.value.as_str() 408 | } 409 | } 410 | fn combine_mut(&self, a: &mut StrType, b: &StrType) { 411 | a.value.push_str(b.value.as_str()); 412 | } 413 | } 414 | 415 | #[test] 416 | fn segment_tree_build() { 417 | let mut rng = thread_rng(); 418 | let vals: Vec> = rng.sample_iter(&Standard) 419 | .map(|i| Wrapping(i)).take(130).collect(); 420 | for i in 0..vals.len() { 421 | let buf: Vec<_> = vals[0..i].iter().cloned().collect(); 422 | println!("{:?}", buf); 423 | let mut buf2 = vec![]; 424 | let n = buf.len(); 425 | buf2.resize(2*n, Wrapping(0)); 426 | for i in 0..n { 427 | buf2[n+i] = buf[i]; 428 | } 429 | let tree1 = SegmentPoint::build(buf, Add); 430 | let tree2 = SegmentPoint::build_noalloc(buf2, Add); 431 | let mut buf = tree1.buf; 432 | let mut buf2 = tree2.buf; 433 | if i > 0 { 434 | buf[0] = Wrapping(0); 435 | buf2[0] = Wrapping(0); 436 | } 437 | println!("build"); 438 | println!("{:?}", buf); 439 | println!("build_noalloc"); 440 | println!("{:?}", buf2); 441 | assert_eq!(buf, buf2); 442 | assert_eq!(buf.len(), 2*n); 443 | } 444 | } 445 | #[test] 446 | fn segment_tree_query() { 447 | let mut rng = thread_rng(); 448 | let vals: Vec = rng.sample_iter(&Standard).take(130).collect(); 449 | for i in 0..vals.len() { 450 | let buf: Vec<_> = vals[0..i].iter().cloned().collect(); 451 | let tree = SegmentPoint::build(buf.clone(), Add); 452 | let sum = StrType::cat(&buf); 453 | let n = buf.len(); 454 | println!("n: {} tree.buf.len: {}", n, tree.buf.len()); 455 | for i in 0..n { 456 | for j in i+1..n+1 { 457 | println!("i: {}, j: {}", i, j); 458 | assert_eq!(tree.query_noiden(i, j), sum.sub(i, j)); 459 | assert_eq!(tree.query_noclone(i, j), MaybeOwned::Owned(sum.sub(i, j))); 460 | } 461 | } 462 | } 463 | } 464 | #[test] 465 | fn segment_tree_query_commut() { 466 | let mut rng = thread_rng(); 467 | let vals: Vec> = rng.sample_iter(&Standard) 468 | .map(|i| Wrapping(i)).take(130).collect(); 469 | for i in 0..vals.len() { 470 | let mut buf: Vec<_> = vals[0..i].iter().cloned().collect(); 471 | let tree = SegmentPoint::build(buf.clone(), Add); 472 | assert_eq!(tree.view(), &buf[..]); 473 | 474 | for i in 1..buf.len() { 475 | let prev = buf[i-1]; 476 | buf[i] += prev; 477 | } 478 | 479 | let n = buf.len(); 480 | println!("n: {} tree.buf.len: {}", n, tree.buf.len()); 481 | for i in 0..n { 482 | for j in i+1..n+1 { 483 | println!("i: {}, j: {}", i, j); 484 | if i == 0 { 485 | assert_eq!(tree.query(i, j), buf[j-1]); 486 | } else { 487 | assert_eq!(tree.query(i, j), buf[j-1] - buf[i-1]); 488 | } 489 | } 490 | } 491 | } 492 | } 493 | #[test] 494 | fn segment_tree_modify() { 495 | let mut rng = thread_rng(); 496 | let vals1: Vec> = rng.sample_iter(&Standard) 497 | .map(|i| Wrapping(i)).take(130).collect(); 498 | let vals2: Vec> = rng.sample_iter(&Standard) 499 | .map(|i| Wrapping(i)).take(130).collect(); 500 | for i in 0..vals1.len() { 501 | let mut order: Vec<_> = (0..i).collect(); 502 | order.shuffle(&mut rng); 503 | let mut buf: Vec<_> = vals1[0..i].iter().cloned().collect(); 504 | let mut tree = SegmentPoint::build(buf.clone(), Add); 505 | for next in order { 506 | tree.modify(next, vals2[next]); 507 | buf[next] = vals2[next]; 508 | let tree2 = SegmentPoint::build(buf.clone(), Add); 509 | assert_eq!(tree.buf[1..], tree2.buf[1..]); 510 | } 511 | } 512 | } 513 | } 514 | --------------------------------------------------------------------------------