pub struct DisjointSetUnion { parent: Vec, sizes: Vec, size: usize, } impl DisjointSetUnion { pub fn new(n: usize) -> DisjointSetUnion { DisjointSetUnion { parent: (0..n).map(|i| i).collect::>(), sizes: vec![1; n], size: n, } } pub fn leader(&mut self, x: usize) -> usize { if x == self.parent[x] { return x; } let px = self.parent[x]; self.parent[x] = self.leader(px); self.parent[x] } pub fn merge(&mut self, x: usize, y: usize) -> bool { let px = self.leader(x); let py = self.leader(y); if px == py { return false; } let (l, s) = if self.sizes[px] < self.sizes[py] { (py, px) } else { (px, py) }; self.parent[s] = l; self.sizes[l] += self.sizes[s]; self.sizes[s] = 0; self.size -= 1; true } } use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use DisjointSetUnion as DSU; fn main() { let (r, w) = (std::io::stdin(), std::io::stdout()); let mut sc = IO::new(r.lock(), w.lock()); let n = sc.read(); let q = sc.read(); let mut dsu = DSU::new(n); let mut sets: BTreeMap> = BTreeMap::new(); for i in 0..n { let mut set = HashSet::new(); set.insert(i); sets.insert(i, set); } for _ in 0..q { let t = sc.read(); match t { 1 => { let u = sc.usize0(); let v = sc.usize0(); let pu = dsu.leader(u); let pv = dsu.leader(v); dsu.merge(u, v); let p = dsu.leader(u); sets.get_mut(&pu).unwrap().remove(&u); sets.get_mut(&pv).unwrap().remove(&v); sets.get_mut(&p).unwrap().insert(u); sets.get_mut(&p).unwrap().insert(v); if sets.get_mut(&pu).unwrap().is_empty() { sets.remove(&pu); } if sets.get_mut(&pv).unwrap().is_empty() { sets.remove(&pv); } } 2 => { let u = sc.usize0(); let size = dsu.sizes[u]; if size == n { println!("{}", -1); } else { let id = dsu.leader(u); let mut set = sets.range(..id).next_back(); if set.is_none() { set = sets.range((id + 1)..).next(); } println!("{}", set.unwrap().1.iter().next().unwrap() + 1); } } _ => unreachable!() } } } pub struct IO(R, std::io::BufWriter); impl IO { pub fn new(r: R, w: W) -> Self { Self(r, std::io::BufWriter::new(w)) } pub fn write(&mut self, s: S) { use std::io::Write; self.1.write_all(s.to_string().as_bytes()).unwrap(); } pub fn read(&mut self) -> T { use std::io::Read; let buf = self.0.by_ref().bytes() .map(|b| b.unwrap()) .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t') .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t') .collect::>(); unsafe { std::str::from_utf8_unchecked(&buf) }.parse().ok().expect("Parse error.") } pub fn chars(&mut self) -> Vec { self.read::().chars().collect() } pub fn usize0(&mut self) -> usize { self.read::() - 1 } pub fn vec(&mut self, n: usize) -> Vec { (0..n).map(|_| self.read()).collect() } }