#include //#include //#pragma GCC optimize("Ofast") using namespace std; #define reps(i,s,n) for(int i = s; i < n; i++) #define rep(i,n) reps(i,0,n) #define Rreps(i,n,e) for(int i = n - 1; i >= e; --i) #define Rrep(i,n) Rreps(i,n,0) #define ALL(a) a.begin(), a.end() using ll = long long; using vec = vector; using mat = vector; ll N,M,H,W,Q,K,A,B; string S; using P = pair; const ll INF = (1LL<<60); template bool chmin(T &a, const T b){ if(a > b) {a = b; return true;} else return false; } template bool chmax(T &a, const T b){ if(a < b) {a = b; return true;} else return false; } template void my_printv(std::vector v,bool endline = true){ if(!v.empty()){ for(std::size_t i{}; i parent, tree_size; public: union_find(unsigned long _n) : parent(_n), tree_size(_n, 1){ for(unsigned long i = 0; i < _n; ++i)parent[i] = i; } ll find(ll x){ while(parent[x] != x)x = parent[x] = parent[parent[x]]; return x; } void merge(ll a, ll b){ a = find(a); b = find(b); if(a==b) return; if(tree_size[a] < tree_size[b])swap(a, b); tree_size[a] += tree_size[b]; parent[b] = a; return; } bool same(ll a, ll b){ a = find(a); b = find(b); return a == b; } }; //uf.mergeのように使う //ufはMAX_N+1でとるか、代入時に0-indexedにする int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); cin>>N>>M; vec b(N); mat color(N); union_find uf(M); rep(i, N){ cin>>b[i]>>A; --b[i]; color[A-1].push_back(i); } ll res = 0; for(vec &v : color){ reps(i, 1, (int)v.size()){ if(!uf.same(b[v[0]], b[v[i]])){ ++res; uf.merge(b[v[0]], b[v[i]]); } } } cout<