use std::io::*; mod disjoint_set { pub struct DisjointSet { parent: Vec, size: Vec, } impl DisjointSet { pub fn new(n: usize) -> DisjointSet { DisjointSet { parent: (0..n).collect(), size: vec![1; n], } } fn root(&mut self, x: usize) -> usize { if x == self.parent[x] { x } else { let tmp = self.parent[x]; self.parent[x] = self.root(tmp); self.parent[x] } } pub fn merge(&mut self, x: usize, y: usize) { let x = self.root(x); let y = self.root(y); if x == y { return; } if self.size[x] > self.size[y] { self.size[x] += self.size[y]; self.parent[y] = x; } else { self.size[y] += self.size[x]; self.parent[x] = y; } } pub fn same(&mut self, x: usize, y: usize) -> bool { self.root(x) == self.root(y) } } } fn main() { let mut s: String = String::new(); std::io::stdin().read_to_string(&mut s).ok(); let mut itr = s.trim().split_whitespace(); let n: usize = itr.next().unwrap().parse().unwrap(); let m: usize = itr.next().unwrap().parse().unwrap(); let mut col: Vec> = vec![vec![]; n]; for _ in 0..n { let b = itr.next().unwrap().parse::().unwrap() - 1; let c = itr.next().unwrap().parse::().unwrap() - 1; col[c].push(b); } let mut ds = disjoint_set::DisjointSet::new(m); let mut ans = 0; for i in 0..n { if col[i].len() <= 1 { continue; } col[i].sort(); col[i].dedup(); for j in 0..col[i].len() - 1 { if !ds.same(col[i][j], col[i][j + 1]) { ds.merge(col[i][j], col[i][j + 1]); ans += 1; } } } println!("{}", ans); }