use std::{cmp::Reverse, collections::BinaryHeap}; fn main() { let n = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().parse::().unwrap() }; let mut la: Vec<_> = (0..(n - 1)) .map(|_| { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse::().unwrap(), iter.next().unwrap().parse::().unwrap() - 1, ) }) .collect(); la.insert(0, (0, 0)); let q = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().parse::().unwrap() }; let queries: Vec<_> = (0..q) .map(|_| { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse::().unwrap(), iter.next().unwrap().parse::().unwrap(), ) }) .collect(); let mut graph = vec![vec![]; n]; for i in 1..n { graph[la[i].1].push(i); } let mut req_levels: Vec> = vec![None; n]; req_levels[0] = Some(0); let mut heap = BinaryHeap::from(vec![(Reverse(0), 0)]); while let Some((Reverse(level), cur)) = heap.pop() { for &next in &graph[cur] { let next_req_level = &mut req_levels[next]; let candidate_req_level = level.max(la[next].0); if next_req_level.is_none() || candidate_req_level < next_req_level.unwrap() { *next_req_level = Some(candidate_req_level); heap.push((Reverse(candidate_req_level), next)); } } } let mut levels: Vec = req_levels .iter() .filter_map(|&rep_level| rep_level) .collect(); levels.sort_unstable(); for &(qt, v) in &queries { if qt == 1 { let ans = levels.partition_point(|&level| level <= v); println!("{}", ans); } else { if let Some(ans) = req_levels[v - 1] { println!("{}", ans); } else { println!("-1"); } } } }