#include // #include using namespace std; // using namespace atcoder; using ll = long long; using ull = unsigned long long; using P = pair; #define rep(i,n) for(ll i = 0;i < (ll)n;i++) #define ALL(x) (x).begin(),(x).end() #define MOD 1000000007 // 2020/12/06 rechecked class UnionFind{ public: vector par; UnionFind(long long size) : par(size,-1){} bool unite(int x,int y){ x = root(x),y = root(y); if(x == y)return false; if(par[y] < par[x])swap(x,y); par[x] += par[y]; par[y] = x; return true; } bool find(int x,int y){ return root(x) == root(y); } int root(int x){ return par[x] < 0 ? x : par[x] = root(par[x]); } int size(int x){ return -par[root(x)]; } }; int main(){ int n,m; cin >> n >> m; UnionFind uf(m); vector col(n,-1); rep(i,n){ int b,c;cin >> b >> c; b--;c--; if(col[c] >= 0)uf.unite(col[c],b); else col[c] = b; } int res = 0; rep(i,m)if(uf.root(i) == i)res += uf.size(i)-1; cout << res << "\n"; return 0; }