using System.Linq; using System.Collections.Generic; using System; public class UnionFind { private int[] data; public UnionFind(int size) { data = new int[size]; for (int i = 0; i < size; i++) data[i] = -1; } public bool Unite(int x, int y) { x = Root(x); y = Root(y); if (x != y) { if (data[y] < data[x]) { var tmp = y; y = x; x = tmp; } data[x] += data[y]; data[y] = x; } return x != y; } public bool IsSameGroup(int x, int y) => Root(x) == Root(y); public int Root(int x) => data[x] < 0 ? x : data[x] = Root(data[x]); public int getMem(int x) => -data[Root(x)]; } public class Hello { static void Main() { string[] line = Console.ReadLine().Trim().Split(' '); var n = int.Parse(line[0]); var m = int.Parse(line[1]); var box = new int[m]; var color = new Dictionary>(); var uf = new UnionFind(n + 1); for (int i = 1; i <= n; i++) { line = Console.ReadLine().Trim().Split(' '); var b = int.Parse(line[0]) - 1; var c = int.Parse(line[1]); if (box[b] == 0) box[b] = i; else uf.Unite(box[b], i); if (color.ContainsKey(c)) color[c].Add(i); else { color[c] = new List(); color[c].Add(i); } } getAns(color, uf); } static void getAns(Dictionary> d, UnionFind uf) { var count = 0; foreach (var x in d) { var cv = x.Value.Count(); if (cv > 1) { var t = x.Value[0]; for (int i = 1; i < cv; i++) { if (uf.Root(t) != x.Value[i]) { uf.Unite(t, x.Value[i]); count++; } } } } Console.WriteLine(count); } }