#include using namespace std; using ll = long long; using ull = unsigned long long; #define v(t) vector #define p(t) pair #define p2(t, s) pair #define vp(t) v(p(t)) #define rep(i, n) for (int i=0,i##_len=((int)(n)); i=0; --i) #define rep2r(i, a, n) for (int i=((int)(n)),i##_len=((int)(a)); i>=i##_len; --i) #define repi(itr, c) for (__typeof((c).begin()) itr=(c).begin(); itr!=(c).end(); ++itr) #define repir(itr, c) for (__typeof((c).rbegin()) itr=(c).rbegin(); itr!=(c).rend(); ++itr) #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define SORT(v, n) sort(v, v+n); #define VSORT(v) sort(v.begin(), v.end()); #define RSORT(x) sort(rall(x)); #define pb push_back #define eb emplace_back #define INF (1e9) #define LINF (1e18) #define PI (acos(-1)) #define EPS (1e-7) #define DEPS (1e-10) // UnionFind struct UnionFind { vector par; UnionFind(int n=0): par(n,-1) {} int find(int x) { if (par[x] < 0) return x; return par[x] = find(par[x]); } bool unite(int x, int y) { x = find(x); y = find(y); if (x == y) return false; if (par[x] > par[y]) swap(x,y); par[x] += par[y]; par[y] = x; return true; } bool same(int x, int y) { return find(x) == find(y);} int size(int x) { return -par[find(x)];} }; int main(){ int n, m; cin >> n >> m; v(v(int)) col(n); rep(i, n) { int bi, ci; cin >> bi >> ci; --bi; --ci; col[ci].pb(bi); } UnionFind uf(n); rep(i, n) rep(j, sz(col[i])-1) uf.unite(col[i][j], col[i][j+1]); int cnt = 0; rep(i, n) if (uf.par[i] < 0) cnt += abs(uf.par[i]) - 1; cout << cnt << endl; return 0; }