use std::collections::HashSet; use proconio::{input, marker::Usize1}; fn main() { input! { n:usize, q:usize, } let mut uf = UnionFindTree::new(n); let mut leaders = (0..n).collect::>(); for _ in 0..q { input! { t:usize, } if t == 1 { input! { u:Usize1, v:Usize1, } if !uf.same(u, v) { let leader_u = uf.root(u); let leader_v = uf.root(v); uf.unite(u, v); if uf.root(u) == leader_u { leaders.remove(&leader_v); } else { leaders.remove(&leader_u); } } } else { input! { v:Usize1, } if uf.size(v) == n { println!("-1"); } else { let leader_v = uf.root(v); let ans = *leaders .iter() .filter(|leader| leader_v != **leader) .next() .unwrap(); println!("{}", ans + 1); } } } } use unionfindtree::*; mod unionfindtree { pub struct UnionFindTree { par: Vec, rank: Vec, size: Vec, } impl UnionFindTree { pub fn new(n: usize) -> Self { Self { par: (0..n).collect::>(), rank: vec![0; n], size: vec![1; n], } } #[allow(dead_code)] pub fn same(&mut self, v1: usize, v2: usize) -> bool { self.root(v1) == self.root(v2) } #[allow(dead_code)] pub fn size(&mut self, v: usize) -> usize { let v_root = self.root(v); self.size[v_root] } #[allow(dead_code)] pub fn root(&mut self, v: usize) -> usize { if self.par[v] != v { self.par[v] = self.root(self.par[v]); } self.par[v] } pub fn unite(&mut self, v1: usize, v2: usize) { let mut v1_root = self.root(v1); let mut v2_root = self.root(v2); if v1_root == v2_root { return; } if self.rank[v1_root] < self.rank[v2_root] { std::mem::swap(&mut v1_root, &mut v2_root); } self.par[v2_root] = v1_root; self.size[v1_root] += self.size[v2_root]; if self.rank[v1_root] == self.rank[v2_root] { self.rank[v1_root] += 1; } } #[allow(dead_code)] pub fn nofcc(&mut self) -> usize { let n = self.par.len(); (0..n) .map(|v| self.root(v)) .collect::>() .len() } } }