Problem:
Bichrome Tree Connectivity

木が与えられます。

はじめ、すべての頂点は白いです。

白い頂点の色を反転すると黒になり、黒い頂点の色を反転すると白になります。

二種類のクエリを処理してください。

一種類目のクエリでは、頂点vの色を反転します。

二種類目のクエリでは、白い頂点vから白い頂点とそれらを結ぶ辺だけを使ってたどり着ける頂点の個数を答えます。

入力

N Q
a_1 b_1
a_2 b_2
:
a_{n-1} b_{n-1}
t_1 v_1
t_2 v_2
:
t_q v_q

t_iが1のとき一種類目のクエリ、2のとき二種類目のクエリであることを表す。

出力

ans_1
ans_2
:
ans_k

二種類目のクエリに対する答えを順に出力せよ。

制約

1 \leq N,Q \leq 10^5

1 \leq a_i,b_i \leq N

1 \leq t_i \leq 2

1 \leq v_i \leq N

与えられるグラフは木である。

t_i=2のとき、頂点v_iは必ず白である。

入力例

10 3
1 2
2 5
2 6
1 4
1 3
3 7
3 8
3 9
9 10
1 3
2 1
2 8

出力例

5
1

Solution in Rust (judge verdict: Accepted)

// ---------- begin Lazy Segment Tree ----------
pub trait TE {
    type T: Clone;
    type E: Clone;
    fn fold(l: Self::T, r: Self::T) -> Self::T;
    fn eval(x: Self::T, f: Self::E) -> Self::T;
    fn merge(g: Self::E, h: Self::E) -> Self::E;
    fn e() -> Self::T;
    fn id() -> Self::E;
}

pub struct LazySegmentTree<R: TE> {
    size: usize,
    bit: usize,
    a: Vec<(R::T, R::E)>,
}

impl <R: TE> LazySegmentTree<R> {
    pub fn new(n: usize) -> LazySegmentTree<R> {
        let mut bit = 0;
        while (1 << bit) < n {
            bit += 1;
        }
        LazySegmentTree {
            size: 1 << bit,
            bit: bit,
            a: vec![(R::e(), R::id()); 2 << bit],
        }
    }
    pub fn build_by(z: &[R::T]) -> LazySegmentTree<R> {
        let n = z.len();
        let mut bit = 0;
        while (1 << bit) < n {
            bit += 1;
        }
        let mut a = vec![(R::e(), R::id()); 2 << bit];
        for (a, z) in a[(1 << bit)..].iter_mut().zip(z.iter()) {
            a.0 = z.clone();
        }
        for i in (1..(1 << bit)).rev() {
            let l = R::eval(a[2 * i].0.clone(), a[2 * i].1.clone());
            let r = R::eval(a[2 * i + 1].0.clone(), a[2 * i + 1].1.clone());
            a[i].0 = R::fold(l, r);
        }
        LazySegmentTree {
            size: 1 << bit,
            bit : bit,
            a: a,
        }
    }
    fn eval(&self, k: usize) -> R::T {
        R::eval(self.a[k].0.clone(), self.a[k].1.clone())
    }
    fn propagate(&mut self, x: usize) {
        let x = x + self.size;
        for i in (1..(self.bit + 1)).rev() {
            let k = x >> i;
            self.a[2 * k].1 = R::merge(self.a[2 * k].1.clone(), self.a[k].1.clone());
            self.a[2 * k + 1].1 = R::merge(self.a[2 * k + 1].1.clone(), self.a[k].1.clone());
            self.a[k].1 = R::id();
            self.a[k].0 = R::fold(self.eval(2 * k), self.eval(2 * k + 1));
        }
    }
    fn save(&mut self, x: usize) {
        let x = x + self.size;
        for i in 1..(self.bit + 1) {
            let k = x >> i;
            self.a[k].0 = R::fold(self.eval(2 * k), self.eval(2 * k + 1));
        }
    }
    pub fn update(&mut self, l: usize, r: usize, op: R::E) {
        self.propagate(l);
        self.propagate(r - 1);
        let mut x = l + self.size;
        let mut y = r + self.size;
        while x < y {
            if x & 1 == 1 {
                self.a[x].1 = R::merge(self.a[x].1.clone(), op.clone());
                x += 1;
            }
            if y & 1 == 1 {
                y -= 1;
                self.a[y].1 = R::merge(self.a[y].1.clone(), op.clone());
            }
            x >>= 1;
            y >>= 1;
        }
        self.save(l);
        self.save(r - 1);
    }
    pub fn find(&mut self, l: usize, r: usize) -> R::T {
        self.propagate(l);
        self.propagate(r - 1);
        let mut x = l + self.size;
        let mut y = r + self.size;
        let mut p = R::e();
        let mut q = R::e();
        while x < y {
            if x & 1 == 1 {
                p = R::fold(p, self.eval(x));
                x += 1;
            }
            if y & 1 == 1 {
                y -= 1;
                q = R::fold(self.eval(y), q);
            }
            x >>= 1;
            y >>= 1;
        }
        R::fold(p, q)
    }
}
// ---------- end Lazy Segment Tree ----------
// ---------- begin Heavy-Light decomposition ----------
struct HLD {
    graph: Vec<Vec<usize>>,
    path_root: Vec<usize>,
    path_parent: Vec<usize>,
    left: Vec<usize>,
    right: Vec<usize>,
}

impl HLD {
    fn new(n: usize) -> Self {
        HLD {
            graph: vec![vec![]; n],
            path_root: vec![],
            path_parent: vec![],
            left: vec![],
            right: vec![],
        }
    }
    fn add_edge(&mut self, a: usize, b: usize) {
        self.graph[a].push(b);
        self.graph[b].push(a);
    }
    fn build(&mut self, root: usize) {
        let mut q = vec![];
        let mut stack = vec![(root, root)];
        let graph = &mut self.graph;
        while let Some((v, p)) = stack.pop() {
            q.push(v);
            for i in 0..graph[v].len() {
                if graph[v][i] == p {
                    graph[v].swap_remove(i);
                    break;
                }
            }
            for &u in &graph[v] {
                stack.push((u, v));
            }
        }
        let n = graph.len();
        let mut size = vec![1; n];
        for &v in q.iter().rev() {
            for i in 0..graph[v].len() {
                let u = graph[v][i];
                size[v] += size[u];
                if size[u] > size[graph[v][0]] {
                    graph[v].swap(0, i);
                }
            }
        }
        let mut path_root = vec![root; n];
        let mut path_parent = vec![root; n];
        let mut left = vec![0; n];
        let mut right = vec![0; n];
        let mut stack = vec![(root, 0)];
        let mut k = 0;
        while let Some((v, op)) = stack.pop() {
            if op == 1 {
                right[v] = k;
                continue;
            }
            left[v] = k;
            k += 1;
            stack.push((v, 1));
            for i in 1..graph[v].len() {
                let u = graph[v][i];
                path_root[u] = u;
                path_parent[u] = v;
                stack.push((u, 0));
            }
            if graph[v].len() > 0 {
                let u = graph[v][0];
                path_root[u] = path_root[v];
                path_parent[u] = path_parent[v];
                stack.push((u, 0));
            }
        }
        self.path_root = path_root;
        self.path_parent = path_parent;
        self.left = left;
        self.right = right;
    }
    fn sub_tree(&self, v: usize) -> (usize, usize) {
        (self.left[v], self.right[v])
    }
    fn path(&self, v: usize, u: usize) -> Vec<(usize, usize)> {
        let path = &self.path_root;
        let parent = &self.path_parent;
        let index = &self.left;
        let mut x = v;
        let mut y = u;
        let mut ans = vec![];
        while path[x] != path[y] {
            if index[x] < index[y] {
                let p = path[y];
                ans.push((index[p], index[y] + 1));
                y = parent[y];
            } else {
                let p = path[x];
                ans.push((index[p], index[x] + 1));
                x = parent[x];
            }
        }
        ans.push((std::cmp::min(index[x], index[y]), std::cmp::max(index[x], index[y]) + 1));
        ans
    }
}
// ---------- end Heavy-Light decomposition ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

struct A;
impl TE for A {
    type T = i32;
    type E = i32;
    fn fold(l: Self::T, r: Self::T) -> Self::T {
        l + r
    }
    fn eval(x: Self::T, f: Self::E) -> Self::T {
        x + f
    }
    fn merge(g: Self::E, h: Self::E) -> Self::E {
        g + h
    }
    fn e() -> Self::T {
        0
    }
    fn id() -> Self::E {
        0
    }
}

struct B;
impl TE for B {
    type T = bool;
    type E = Option<bool>;
    fn fold(l: Self::T, r: Self::T) -> Self::T {
        l && r
    }
    fn eval(x: Self::T, f: Self::E) -> Self::T {
        if f.is_none() {x} else {f.unwrap()}
    }
    fn merge(g: Self::E, h: Self::E) -> Self::E {
        if h.is_none() {g} else {h}
    }
    fn e() -> Self::T {
        true
    }
    fn id() -> Self::E {
        None
    }
}

use std::io::Write;

fn run() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    input! {
        n: usize,
        q: usize,
        e: [(usize1, usize1); n - 1],
        ask: [(usize, usize1); q],
    }
    let mut hld = HLD::new(n);
    for (a, b) in e {
        hld.add_edge(a, b);
    }
    let root = 0;
    hld.build(root);
    let hld = hld;
    let mut white = LazySegmentTree::<B>::new(n);
    let mut sum = LazySegmentTree::<A>::new(n);
    for i in 0..n {
        let (l, r) = hld.sub_tree(i);
        sum.update(l, l + 1, (r - l) as i32);
    }
    for (t, v) in ask {
        /*
        for i in 0..n {
            let (l, _) = hld.sub_tree(i);
            print!("{}: ({}, {}), ", i + 1, sum.find(l, l + 1), white.find(l, l + 1));
        }
        println!();
        */
        if t == 1 {
            let (l, _) = hld.sub_tree(v);
            let op = white.find(l, l + 1);
            white.update(l, l + 1, Some(true));
            let val = if op {1} else {-1} * sum.find(l, l + 1);
            let path = hld.path(root, v);
            for (l, r) in path {
                if !white.find(l, r) {
                    let mut x = l;
                    let mut y = r;
                    while y - x > 1 {
                        let m = (y + x) / 2;
                        if !white.find(m, r) {
                            x = m;
                        } else {
                            y = m;
                        }
                    }
                    sum.update(x, r, -val);
                    break;
                } else {
                    sum.update(l, r, -val);
                }
            }
            white.update(l, l + 1, Some(!op));
            sum.update(l, l + 1, val);
        } else {
            let path = hld.path(root, v);
            let mut u = hld.sub_tree(v).0;
            for (l, r) in path {
                if !white.find(l, r) {
                    let mut x = l;
                    let mut y = r;
                    while y - x > 1 {
                        let m = (x + y) / 2;
                        if !white.find(m, r) {
                            x = m;
                        } else {
                            y = m;
                        }
                    }
                    if x + 1 < r {
                        u = x + 1;
                    }
                    break;
                } else {
                    u = l;
                }
            }
            let ans = sum.find(u, u + 1);
            writeln!(out, "{}", ans).ok();
        }
    }
}

fn main() {
    run();
}