Skip to main content

HeavyLightDecomposition

Struct HeavyLightDecomposition 

Source
pub struct HeavyLightDecomposition {
    pub par: Vec<usize>,
    size: Vec<usize>,
    head: Vec<usize>,
    pub vidx: Vec<usize>,
}

Fields§

§par: Vec<usize>§size: Vec<usize>§head: Vec<usize>§vidx: Vec<usize>

Implementations§

Source§

impl HeavyLightDecomposition

Source

pub fn new(root: usize, graph: &mut UndirectedSparseGraph) -> Self

Examples found in repository?
crates/library_checker/src/tree/lca.rs (line 25)
19pub fn lca_hld(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, q, p: [usize]);
23    let edges = p.take(n - 1).enumerate().map(|(i, p)| (i + 1, p)).collect();
24    let mut graph = UndirectedSparseGraph::from_edges(n, edges);
25    let hld = HeavyLightDecomposition::new(0, &mut graph);
26    for (u, v) in scanner.iter::<(usize, usize)>().take(q) {
27        writeln!(writer, "{}", hld.lca(u, v)).ok();
28    }
29}
More examples
Hide additional examples
crates/library_checker/src/tree/vertex_add_path_sum.rs (line 20)
16pub fn vertex_add_path_sum(reader: impl Read, mut writer: impl Write) {
17    let s = read_all_unchecked(reader);
18    let mut scanner = Scanner::new(&s);
19    scan!(scanner, n, q, a: [i64; n], (mut graph, _): @TreeGraphScanner::<usize, ()>::new(n));
20    let hld = HeavyLightDecomposition::new(0, &mut graph);
21    let mut bit = BinaryIndexedTree::<AdditiveOperation<_>>::new(n);
22    for (i, a) in a.iter().cloned().enumerate() {
23        bit.update(hld.vidx[i], a);
24    }
25    for _ in 0..q {
26        scan!(scanner, query: Query);
27        match query {
28            Query::Add { p, x } => {
29                bit.update(hld.vidx[p], x);
30            }
31            Query::Sum { u, v } => {
32                writeln!(
33                    writer,
34                    "{}",
35                    hld.query::<AdditiveOperation<_>, _>(u, v, false, |l, r| bit.fold(l, r))
36                )
37                .ok();
38            }
39        }
40    }
41}
crates/aizu_online_judge/src/grl/grl_5_e.rs (line 29)
19pub fn grl_5_e(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, c: [SizedCollect<usize>]);
23    let edges = c
24        .take(n)
25        .enumerate()
26        .flat_map(|(u, it)| it.into_iter().map(move |v| (u, v)))
27        .collect();
28    let mut graph = UndirectedSparseGraph::from_edges(n, edges);
29    let hld = HeavyLightDecomposition::new(0, &mut graph);
30    type M = (AdditiveOperation<u64>, AdditiveOperation<u64>);
31    let mut seg = LazySegmentTree::<RangeSumRangeAdd<_>>::from_vec(vec![(0u64, 1u64); n]);
32
33    scan!(scanner, q);
34    for _ in 0..q {
35        scan!(scanner, query: Query);
36        match query {
37            Query::Add { v, w } => {
38                hld.update(0, v, true, |l, r| seg.update(l..r, w));
39            }
40            Query::Get { u } => {
41                let ans = hld.query::<M, _>(0, u, true, |l, r| seg.fold(l..r)).0;
42                writeln!(writer, "{}", ans).ok();
43            }
44        }
45    }
46}
crates/library_checker/src/tree/vertex_set_path_composite.rs (line 23)
19pub fn vertex_set_path_composite(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, q, ab: [(MInt998244353, MInt998244353); n], (mut graph, _): @TreeGraphScanner::<usize, ()>::new(n));
23    let hld = HeavyLightDecomposition::new(0, &mut graph);
24    let mut nab = vec![(MInt998244353::default(), MInt998244353::default()); n];
25    for i in 0..n {
26        nab[hld.vidx[i]] = ab[i];
27    }
28    let mut seg1 = SegmentTree::<LinearOperation<_>>::from_vec(nab.clone());
29    let mut seg2 = SegmentTree::<ReverseOperation<LinearOperation<_>>>::from_vec(nab);
30    for _ in 0..q {
31        scan!(scanner, query: Query);
32        match query {
33            Query::Set { p, cd } => {
34                seg1.set(hld.vidx[p], cd);
35                seg2.set(hld.vidx[p], cd);
36            }
37            Query::Apply { u, v, x } => {
38                let (a, b) = hld.query_noncom::<LinearOperation<_>, _, _>(
39                    u,
40                    v,
41                    false,
42                    |l, r| seg1.fold(l..r),
43                    |l, r| seg2.fold(l..r),
44                );
45                writeln!(writer, "{}", a * x + b).ok();
46            }
47        }
48    }
49}
Source

fn dfs_size(&mut self, u: usize, p: usize, graph: &mut UndirectedSparseGraph)

Examples found in repository?
crates/competitive/src/tree/heavy_light_decomposition.rs (line 32)
22    fn dfs_size(&mut self, u: usize, p: usize, graph: &mut UndirectedSparseGraph) {
23        self.par[u] = p;
24        self.size[u] = 1;
25        let base = graph.start[u];
26        if graph.adjacencies(u).len() > 1 && graph.adjacencies(u).next().unwrap().to == p {
27            graph.elist.swap(base, base + 1);
28        }
29        for i in base..graph.start[u + 1] {
30            let a = graph.elist[i];
31            if a.to != p {
32                self.dfs_size(a.to, u, graph);
33                self.size[u] += self.size[a.to];
34                if self.size[graph.elist[base].to] < self.size[a.to] {
35                    graph.elist.swap(base, i);
36                }
37            }
38        }
39    }
40
41    fn dfs_hld(&mut self, u: usize, p: usize, t: &mut usize, graph: &UndirectedSparseGraph) {
42        self.vidx[u] = *t;
43        *t += 1;
44        let mut adjacencies = graph.adjacencies(u).filter(|a| a.to != p);
45        if let Some(a) = adjacencies.next() {
46            self.head[a.to] = self.head[u];
47            self.dfs_hld(a.to, u, t, graph);
48        }
49        for a in adjacencies {
50            self.head[a.to] = a.to;
51            self.dfs_hld(a.to, u, t, graph);
52        }
53    }
54
55    fn build(&mut self, root: usize, graph: &mut UndirectedSparseGraph) {
56        self.head[root] = root;
57        self.dfs_size(root, graph.vertices_size(), graph);
58        let mut t = 0;
59        self.dfs_hld(root, graph.vertices_size(), &mut t, graph);
60    }
Source

fn dfs_hld( &mut self, u: usize, p: usize, t: &mut usize, graph: &UndirectedSparseGraph, )

Examples found in repository?
crates/competitive/src/tree/heavy_light_decomposition.rs (line 47)
41    fn dfs_hld(&mut self, u: usize, p: usize, t: &mut usize, graph: &UndirectedSparseGraph) {
42        self.vidx[u] = *t;
43        *t += 1;
44        let mut adjacencies = graph.adjacencies(u).filter(|a| a.to != p);
45        if let Some(a) = adjacencies.next() {
46            self.head[a.to] = self.head[u];
47            self.dfs_hld(a.to, u, t, graph);
48        }
49        for a in adjacencies {
50            self.head[a.to] = a.to;
51            self.dfs_hld(a.to, u, t, graph);
52        }
53    }
54
55    fn build(&mut self, root: usize, graph: &mut UndirectedSparseGraph) {
56        self.head[root] = root;
57        self.dfs_size(root, graph.vertices_size(), graph);
58        let mut t = 0;
59        self.dfs_hld(root, graph.vertices_size(), &mut t, graph);
60    }
Source

fn build(&mut self, root: usize, graph: &mut UndirectedSparseGraph)

Examples found in repository?
crates/competitive/src/tree/heavy_light_decomposition.rs (line 18)
11    pub fn new(root: usize, graph: &mut UndirectedSparseGraph) -> Self {
12        let mut self_ = Self {
13            par: vec![0; graph.vertices_size()],
14            size: vec![0; graph.vertices_size()],
15            head: vec![0; graph.vertices_size()],
16            vidx: vec![0; graph.vertices_size()],
17        };
18        self_.build(root, graph);
19        self_
20    }
Source

pub fn lca(&self, u: usize, v: usize) -> usize

Examples found in repository?
crates/library_checker/src/tree/lca.rs (line 27)
19pub fn lca_hld(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, q, p: [usize]);
23    let edges = p.take(n - 1).enumerate().map(|(i, p)| (i + 1, p)).collect();
24    let mut graph = UndirectedSparseGraph::from_edges(n, edges);
25    let hld = HeavyLightDecomposition::new(0, &mut graph);
26    for (u, v) in scanner.iter::<(usize, usize)>().take(q) {
27        writeln!(writer, "{}", hld.lca(u, v)).ok();
28    }
29}
Source

pub fn update<F: FnMut(usize, usize)>( &self, u: usize, v: usize, is_edge: bool, f: F, )

Examples found in repository?
crates/aizu_online_judge/src/grl/grl_5_e.rs (line 38)
19pub fn grl_5_e(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, c: [SizedCollect<usize>]);
23    let edges = c
24        .take(n)
25        .enumerate()
26        .flat_map(|(u, it)| it.into_iter().map(move |v| (u, v)))
27        .collect();
28    let mut graph = UndirectedSparseGraph::from_edges(n, edges);
29    let hld = HeavyLightDecomposition::new(0, &mut graph);
30    type M = (AdditiveOperation<u64>, AdditiveOperation<u64>);
31    let mut seg = LazySegmentTree::<RangeSumRangeAdd<_>>::from_vec(vec![(0u64, 1u64); n]);
32
33    scan!(scanner, q);
34    for _ in 0..q {
35        scan!(scanner, query: Query);
36        match query {
37            Query::Add { v, w } => {
38                hld.update(0, v, true, |l, r| seg.update(l..r, w));
39            }
40            Query::Get { u } => {
41                let ans = hld.query::<M, _>(0, u, true, |l, r| seg.fold(l..r)).0;
42                writeln!(writer, "{}", ans).ok();
43            }
44        }
45    }
46}
Source

pub fn query<M: Monoid, F: FnMut(usize, usize) -> M::T>( &self, u: usize, v: usize, is_edge: bool, f: F, ) -> M::T

Examples found in repository?
crates/library_checker/src/tree/vertex_add_path_sum.rs (line 35)
16pub fn vertex_add_path_sum(reader: impl Read, mut writer: impl Write) {
17    let s = read_all_unchecked(reader);
18    let mut scanner = Scanner::new(&s);
19    scan!(scanner, n, q, a: [i64; n], (mut graph, _): @TreeGraphScanner::<usize, ()>::new(n));
20    let hld = HeavyLightDecomposition::new(0, &mut graph);
21    let mut bit = BinaryIndexedTree::<AdditiveOperation<_>>::new(n);
22    for (i, a) in a.iter().cloned().enumerate() {
23        bit.update(hld.vidx[i], a);
24    }
25    for _ in 0..q {
26        scan!(scanner, query: Query);
27        match query {
28            Query::Add { p, x } => {
29                bit.update(hld.vidx[p], x);
30            }
31            Query::Sum { u, v } => {
32                writeln!(
33                    writer,
34                    "{}",
35                    hld.query::<AdditiveOperation<_>, _>(u, v, false, |l, r| bit.fold(l, r))
36                )
37                .ok();
38            }
39        }
40    }
41}
More examples
Hide additional examples
crates/aizu_online_judge/src/grl/grl_5_e.rs (line 41)
19pub fn grl_5_e(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, c: [SizedCollect<usize>]);
23    let edges = c
24        .take(n)
25        .enumerate()
26        .flat_map(|(u, it)| it.into_iter().map(move |v| (u, v)))
27        .collect();
28    let mut graph = UndirectedSparseGraph::from_edges(n, edges);
29    let hld = HeavyLightDecomposition::new(0, &mut graph);
30    type M = (AdditiveOperation<u64>, AdditiveOperation<u64>);
31    let mut seg = LazySegmentTree::<RangeSumRangeAdd<_>>::from_vec(vec![(0u64, 1u64); n]);
32
33    scan!(scanner, q);
34    for _ in 0..q {
35        scan!(scanner, query: Query);
36        match query {
37            Query::Add { v, w } => {
38                hld.update(0, v, true, |l, r| seg.update(l..r, w));
39            }
40            Query::Get { u } => {
41                let ans = hld.query::<M, _>(0, u, true, |l, r| seg.fold(l..r)).0;
42                writeln!(writer, "{}", ans).ok();
43            }
44        }
45    }
46}
Source

pub fn query_noncom<M: Monoid, F1: FnMut(usize, usize) -> M::T, F2: FnMut(usize, usize) -> M::T>( &self, u: usize, v: usize, is_edge: bool, f1: F1, f2: F2, ) -> M::T

Examples found in repository?
crates/library_checker/src/tree/vertex_set_path_composite.rs (lines 38-44)
19pub fn vertex_set_path_composite(reader: impl Read, mut writer: impl Write) {
20    let s = read_all_unchecked(reader);
21    let mut scanner = Scanner::new(&s);
22    scan!(scanner, n, q, ab: [(MInt998244353, MInt998244353); n], (mut graph, _): @TreeGraphScanner::<usize, ()>::new(n));
23    let hld = HeavyLightDecomposition::new(0, &mut graph);
24    let mut nab = vec![(MInt998244353::default(), MInt998244353::default()); n];
25    for i in 0..n {
26        nab[hld.vidx[i]] = ab[i];
27    }
28    let mut seg1 = SegmentTree::<LinearOperation<_>>::from_vec(nab.clone());
29    let mut seg2 = SegmentTree::<ReverseOperation<LinearOperation<_>>>::from_vec(nab);
30    for _ in 0..q {
31        scan!(scanner, query: Query);
32        match query {
33            Query::Set { p, cd } => {
34                seg1.set(hld.vidx[p], cd);
35                seg2.set(hld.vidx[p], cd);
36            }
37            Query::Apply { u, v, x } => {
38                let (a, b) = hld.query_noncom::<LinearOperation<_>, _, _>(
39                    u,
40                    v,
41                    false,
42                    |l, r| seg1.fold(l..r),
43                    |l, r| seg2.fold(l..r),
44                );
45                writeln!(writer, "{}", a * x + b).ok();
46            }
47        }
48    }
49}

Auto Trait Implementations§

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> 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> ToArrayVecScalar for T

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.