#[allow(unused_imports)] use std::{ convert::{Infallible, TryFrom, TryInto as _}, fmt::{self, Debug, Display, Formatter,}, fs::File, hash::{Hash, Hasher, BuildHasherDefault}, iter::{Product, Sum}, marker::PhantomData, ops::{Add, AddAssign, Sub, SubAssign, Div, DivAssign, Mul, MulAssign, Neg, RangeBounds, BitAnd, BitAndAssign, BitOr, BitXor, BitXorAssign, BitOrAssign, Index, IndexMut}, str::FromStr, sync::{atomic::{self, AtomicU32, AtomicU64}, Once}, collections::{*, btree_set::Range, btree_map::Range as BTreeRange}, mem::{take, swap}, cmp::{self, Reverse, Ordering, Eq, PartialEq, PartialOrd}, thread::LocalKey, f64::consts::PI, time::Instant, cell::RefCell, io::{self, stdin, Read, read_to_string, BufWriter, BufReader, stdout, Write}, ptr::null_mut, println, print,debug_assert,debug_assert_eq,debug_assert_ne, matches }; #[allow(unused_imports)] use core::panic; pub mod fxhash { use std::hash::BuildHasherDefault; const K: u64 = 0x517c_c1b7_2722_0a95; #[derive(Default)] pub struct FxHasher { pub hash: u64, } impl FxHasher { #[inline(always)] fn mix_u64(mut h: u64, x: u64) -> u64 { h = h.rotate_left(5) ^ x; h = h.wrapping_mul(K); let x2 = x ^ (x >> 33) ^ (x << 11); h = h.rotate_left(5) ^ x2; h = h.wrapping_mul(K); h } #[inline(always)] fn write_u64_impl(&mut self, x: u64) { self.hash = Self::mix_u64(self.hash, x); } } impl std::hash::Hasher for FxHasher { #[inline(always)] fn finish(&self) -> u64 { self.hash } #[inline(always)] fn write(&mut self, bytes: &[u8]) { let mut h = self.hash; for &b in bytes { h = h.rotate_left(5) ^ (b as u64); h = h.wrapping_mul(K); } self.hash = h; } #[inline(always)] fn write_u64(&mut self, i: u64) { self.write_u64_impl(i); } #[inline(always)] fn write_u32(&mut self, i: u32) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_u16(&mut self, i: u16) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_u8 (&mut self, i: u8 ) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_usize(&mut self, i: usize) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_i64(&mut self, i: i64) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_i32(&mut self, i: i32) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_i16(&mut self, i: i16) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_i8 (&mut self, i: i8 ) { self.write_u64_impl(i as u64); } #[inline(always)] fn write_isize(&mut self, i: isize) { self.write_u64_impl(i as u64); } } pub type FxBuildHasher = BuildHasherDefault; pub type FxMap = std::collections::HashMap; pub type FxSet = std::collections::HashSet; } pub fn gcd(mut a: i64, mut b: i64)->i64{a=a.abs();b=b.abs();if a==0{return b;}else if b==0{return a;}let l1 = a.trailing_zeros();let l2 = b.trailing_zeros(); a >>= l1; b >>= l2;while a!=b{let x = (a^b).trailing_zeros();if a>x;}a << l1.min(l2)} pub fn gcd_i32(mut a: i32, mut b: i32)->i32{a=a.abs();b=b.abs();if a==0{return b;}else if b==0{return a;}let l1 = a.trailing_zeros();let l2 = b.trailing_zeros(); a >>= l1; b >>= l2;while a!=b{let x = (a^b).trailing_zeros();if a>x;}a << l1.min(l2)} pub fn factorial_i64(n: usize)->(Vec, Vec){ let mut res = vec![1; n+1];let mut inv = vec![1; n+1];for i in 0..n{ res[i+1] = (res[i]*(i+1)as i64)%MOD; } inv[n] = mod_inverse(res[n], MOD);for i in (0..n).rev(){ inv[i] = inv[i+1]*(i+1) as i64%MOD; }(res, inv) } pub fn floor(a:i64, b:i64)->i64{let res=(a%b+b)%b;(a-res)/b} pub fn modulo(a: i64, b: i64)->i64{(a%b+b)%b} pub fn extended_gcd(a:i64,b:i64)->(i64,i64,i64) {if b==0{(a,1,0)}else{let(g,x,y)=extended_gcd(b,a%b);(g,y,x-floor(a,b)*y)}} pub fn mod_inverse(a:i64,m:i64)->i64{let(_,x,_) =extended_gcd(a,m);(x%m+m)%m} pub fn comb(a: i64, b: i64, f: &Vec<(i64, i64)>)->i64{ if aVec<(i64, i64)>{ let mut f=vec![(1i64,1i64),(1, 1)];let mut z = 1i64; let mut inv = vec![0; x as usize+10];inv[1] = 1; for i in 2..x+1{z=(z*i)%MOD; let w=(MOD-inv[(MOD%i)as usize]*(MOD/i)%MOD)%MOD; inv[i as usize] = w; f.push((z, (f[i as usize-1].1*w)%MOD));}return f;} pub fn fast_mod_pow(mut x: i64,p: usize, m: i64)->i64{ x %= m; let mut res=1;let mut t=x;let mut z=p;while z > 0{ if z%2==1{res = (res*t)%m;}t = (t*t)%m;z /= 2; }res} pub trait SortD{ fn sort_d(&mut self); } impl SortD for Vec{ fn sort_d(&mut self) {self.sort_by(|u, v| v.cmp(&u));} } pub trait Mx{fn max(&self, rhs: Self)->Self;} impl Mx for f64{ fn max(&self, rhs: Self)->Self{if *self < rhs{ rhs } else { *self } }} pub trait Mi{ fn min(&self, rhs: Self)->Self; } impl Mi for f64{ fn min(&self, rhs: Self)->Self{ if *self > rhs{ rhs } else { *self } } } pub trait Chmax: PartialOrd + Copy {fn chmax(&mut self, rhs: Self) {if *self < rhs { *self = rhs; }}} impl Chmax for T {} pub trait Chmin: PartialOrd + Copy {fn chmin(&mut self, rhs: Self) {if *self > rhs { *self = rhs; }}} impl Chmin for T {} #[allow(unused)] use proconio::{*, marker::*}; #[allow(unused)] use fxhash::{FxMap, FxSet}; #[allow(unused)] use ac_library::{*}; pub struct MintCombination{ fact: Vec, inv_fact: Vec, inv: Vec, } impl MintCombination{ pub fn new(n: usize)->Self { let mut fact = vec![MI::new(1); n+1]; let mut inv_fact = vec![MI::new(0); n+1]; let mut inv = vec![MI::new(1); n+1]; for i in 0..n{ fact[i+1] = fact[i]*(i+1); } inv_fact[n] = MI::new(1)/fact[n]; for i in (0..n).rev(){ inv_fact[i] = inv_fact[i+1]*(i+1); inv[i+1] = fact[i]*inv_fact[i+1]; } MintCombination { fact, inv_fact, inv } } #[inline] pub fn inv(&self, x: usize)->MI{ self.inv[x] } #[inline] pub fn f(&self, x: usize)->MI{ self.fact[x] } #[inline] pub fn fi(&self, x: usize)->MI{ self.inv_fact[x] } #[inline] pub fn p(&self, x: usize, y: usize)->MI{ if x < y{MI::new(0)} else {self.fact[x]*self.inv_fact[x-y]} } #[inline] pub fn c(&self, x: usize, y: usize)->MI{ if x < y{return MI::new(0);} self.fact[x]*self.inv_fact[y]*self.inv_fact[x-y] } } #[allow(dead_code)] const INF: i64 = 1<<60; #[allow(dead_code)] const I: i32 = 1<<30; #[allow(dead_code)] const MOD: i64 = 998244353; #[allow(dead_code)] const D: [(usize, usize); 4] = [(1, 0), (0, 1), (!0, 0), (0, !0)]; #[allow(dead_code)] pub fn c2d(c: u8)->(usize, usize){match c{b'U'=>(!0,0),b'D'=>(1,0),b'L'=>(0,!0),b'R'=>(0,1),_=>unreachable!()}} #[allow(dead_code)] pub fn c2d_i64(c: u8)->(i64, i64){match c{b'U'=>(-1,0),b'D'=>(1,0),b'L'=>(0,-1),b'R'=>(0,1),_=>unreachable!()}} #[allow(dead_code)] pub fn join2str(v: &[T])->String{v.iter().map(|x| x.to_string()).collect::>().join(" ")} #[allow(dead_code)] pub fn join2nospace(v: &[T])->String{v.iter().map(|x| x.to_string()).collect::>().join("")} #[allow(dead_code)] const D2: [(usize, usize); 8] = [(1, 0), (1, 1), (0, 1), (!0, 1), (!0, 0), (!0, !0), (0, !0), (1, !0)]; #[derive(Clone, Debug)] pub struct CSR{ n: usize, ac: Vec, edge: Vec, } impl CSR{ pub fn new(n: usize, es: &[(usize, usize)])->Self{ let mut ac = vec![0; n+1]; for &(u, _) in es{ ac[u+1] += 1; } for i in 0..n{ ac[i+1] += ac[i]; } let mut cnt = ac.clone(); let mut edge = vec![0; ac[n]]; for &(u, v) in es{ edge[cnt[u]] = v; cnt[u] += 1; } CSR { n, ac, edge } } pub fn undirected_new(n: usize, es: &[(usize, usize)])->Self{ let mut e = Vec::with_capacity(es.len()<<1); for &(u, v) in es{ e.push((u, v)); e.push((v, u)); } Self::new(n, &e) } #[inline] pub fn len(&self)->usize{ self.n } #[inline] pub fn adj(&self, idx: usize)->&[usize]{ &self.edge[self.ac[idx]..self.ac[idx+1]] } #[inline] pub fn adj_mut(&mut self, idx: usize)->&mut [usize]{ &mut self.edge[self.ac[idx]..self.ac[idx+1]] } } impl Index for CSR{ type Output = [usize]; fn index(&self, index: usize) -> &Self::Output { &self.edge[self.ac[index]..self.ac[index+1]] } } impl IndexMut for CSR{ fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.edge[self.ac[index]..self.ac[index+1]] } } #[derive(Clone, Debug)] pub struct UnweightedGraph{ n: usize, edge: CSR, } impl UnweightedGraph{ pub fn new(n: usize, edge: &[(usize, usize)])->Self{ UnweightedGraph{n, edge: CSR::undirected_new(n, &edge)} } pub fn bfs(&self, p: usize)->Vec{ let mut dist = vec![!0; self.n]; dist[p] = 0; let mut stack = VecDeque::new(); stack.push_back(p); while let Some(p) = stack.pop_front(){ for &nex in &self.edge[p]{ if dist[nex]==!0{ dist[nex] = dist[p]+1; stack.push_back(nex); } } } dist } pub fn farthest_point(&self, p: usize)->(usize, usize){ let d = self.bfs(p); let (mut res, mut mx) = (p, 0); for i in 0..self.n{ if d[i]!=!0 && d[i] > mx{ mx = d[i]; res = i; } } (mx, res) } pub fn n(&self)->usize{self.n} pub fn build_path(&self, u: usize, v: usize)->Option>{ let dist = self.bfs(u); if dist[v]==!0{return None} let mut res = Vec::new(); res.push(v); let mut p = v; while p != u{ let mut nx = 0; for &nex in &self.edge[p]{ if dist[nex]!=!0 && dist[nex]+1==dist[p]{ nx = nex; break; } } p = nx; res.push(p); } res.reverse(); Some(res) } pub fn path(&self, u: usize, v: usize)->Vec{ let dist = self.bfs(u); let mut res = Vec::new(); res.push(v); let mut p = v; while p != u{ let mut nx = 0; for &nex in &self.edge[p]{ if dist[nex]!=!0 && dist[nex]+1==dist[p]{ nx = nex; break; } } p = nx; res.push(p); } res.reverse(); res } } impl Index for UnweightedGraph{ type Output = [usize]; fn index(&self, index: usize) -> &Self::Output { &self.edge[index] } } pub struct CentroidDecomposition { pre: Vec, level: Vec, } impl CentroidDecomposition { pub fn new(tree: &UnweightedGraph) -> Self { let n = tree.n; let mut pp = vec![!0; n]; let mut level = vec![!0; n]; let mut size = CentroidDecomposition::size_dfs(n, tree); let mut stack = VecDeque::from([(0, !0, 0)]); for _ in 0..n { let (mut p, pre, d) = stack.pop_front().unwrap(); let mut non = true; while non { non = false; for &nex in &tree[p] { if level[nex] == !0 && size[nex] * 2 > size[p] { size.swap(p, nex); (size[p], p, non) = (size[nex] - size[p], nex, true); break; } } } pp[p] = pre; level[p] = d; if size[p] > 1 { for &nex in &tree[p] { if level[nex] == !0 { stack.push_back((nex, p, d+1)); } } } } CentroidDecomposition { pre: pp, level } } #[inline] pub fn parent(&self, v: usize) -> usize { self.pre[v] } #[inline] pub fn depth(&self, v: usize) -> usize { self.level[v] } fn size_dfs(n: usize, edge: &UnweightedGraph) -> Vec { let mut size = vec![1; n]; let mut stack = Vec::from([(0, !0)]); let mut query = Vec::new(); while let Some((p, pre)) = stack.pop() { for &nex in &edge[p] { if pre == nex {continue} stack.push((nex, p)); query.push((nex, p)); } } for &(p, pre) in query.iter().rev() { size[pre] += size[p]; } size } #[inline] pub fn lca(&self, mut u: usize, mut v: usize) -> usize { let (du, dv) = (self.level[u], self.level[v]); if du > dv { for _ in 0..du - dv { u = self.pre[u]; } } else { for _ in 0..dv - du { v = self.pre[v]; } } while u != v { (u, v) = (self.pre[u], self.pre[v]) } u } #[inline] pub fn ancestors(&self, v: usize) -> impl Iterator + '_ { std::iter::successors(Some(v), |&v| { let p = self.pre[v]; (p != !0).then_some(p) }) } } struct M; impl Monoid for M{ type S = i32; fn identity() -> Self::S { 0 } fn binary_operation(&a: &Self::S, &b: &Self::S) -> Self::S { a.max(b) } } #[derive(Clone, Debug)] pub struct SparseTableMI { table: Vec>, } impl SparseTableMI { pub fn build(a: &Vec) -> Self { Self::build_by_key(a, |x| x) } #[inline] pub fn query(&self, l: usize, r: usize) -> T { self.query_by_key(l, r, |x| x) } } impl SparseTableMI { pub fn build_by_key K>(a: &[T], key: F) -> Self { let n = a.len(); let mut table: Vec> = Vec::new(); table.push(a.to_vec()); let mut k = 1; while 1< K>(&self, l: usize, r: usize, key: F) -> T { assert!(l < r && r <= self.table[0].len()); let s = r-l; let k = (usize::BITS-1-s.leading_zeros())as usize; let w = 1<, data: SparseTableMI, dist: Box<[usize]> } impl STLCA { pub fn new(p: usize, edge: &UnweightedGraph) -> Self{ let n = edge.n; let mut int = vec![0; n]; let mut data = Vec::with_capacity(2*n); let mut dist = vec![0; n].into_boxed_slice(); fn lca_dfs(p: usize, pre: usize, edge: &UnweightedGraph, data: &mut Vec, int: &mut [usize], dist: &mut [usize]){ int[p] = data.len(); data.push(p); for &nex in &edge[p]{ if nex==pre{continue;} dist[nex] = dist[p]+1; lca_dfs(nex, p, edge, data, int, dist); data.push(p); } } lca_dfs(p, !0, edge, &mut data, &mut int, &mut dist); let data = SparseTableMI::build_by_key(&data, |v| dist[v]); STLCA {int, data, dist} } #[inline] pub fn lca(&self, mut u: usize, mut v: usize)->usize{ if self.int[u] > self.int[v]{std::mem::swap(&mut u, &mut v);} self.data.query_by_key(self.int[u], self.int[v]+1, |v| self.dist[v]) } #[inline] pub fn distance(&self, u: usize, v: usize)->usize{ let p = self.lca(u, v); self.dist[u]+self.dist[v]-2*self.dist[p] } } #[allow(unused)] type MI = StaticModInt; const MULTI: bool = false; #[fastout] fn solve(){ input!{ n: usize, e: [(Usize1, Usize1); n-1], q: usize, query: [(u8, Usize1); q], } let edge = UnweightedGraph::new(n, &e); let cent = CentroidDecomposition::new(&edge); let lca = STLCA::new(0, &edge); let mut f = vec![false; n]; let mut cnt = vec![0; n]; for i in 0..n{ for p in cent.ancestors(i) { cnt[p]+=1; } } let mut dist = (0..n).map(|i| Segtree::::new(cnt[i])).collect::>(); for &(t, p) in &query{ if t==1 { if f[p] { for x in cent.ancestors(p) { let d = lca.distance(x, p); let pre = dist[x].get(d); dist[x].set(d, pre-1); } } else { for x in cent.ancestors(p) { let d = lca.distance(x, p); let pre = dist[x].get(d); dist[x].set(d, pre+1); } } f[p]=!f[p]; } else { let mut res = 1<<30; for x in cent.ancestors(p) { let d = lca.distance(x, p); let z = dist[x].max_right(0, |&v|v==0); if z < cnt[x]{ res.chmin(z+d); } } println!("{}", res); } } } fn main() { if MULTI{ input!{ t: usize, } for _ in 0..t{ solve(); } } else { solve(); } }