#include using namespace std; using ll = long long; template using vec = vector; template using vvec = vector>; template bool chmin(T& a,T b){if(a>b) {a = b; return true;} return false;} template bool chmax(T& a,T b){if(a=0;i--) #define all(x) (x).begin(),(x).end() #define debug(x) cerr << #x << " = " << (x) << endl; class UnionFind{ private: vec p,s; int cnt; public: UnionFind(){} UnionFind(int N):cnt(N),s(N,1),p(N){ iota(p.begin(),p.end(),0); } int find(int x){ if(p[x]==x) return x; else return p[x] = find(p[x]); } void unite(int x,int y){ x = find(x); y = find(y); if(x==y) return; if(s[x]>s[y]) swap(x,y); p[x] = y; s[y] += s[x]; cnt--; } int operator[](const int x){return find(x);} bool is_same_set(int x,int y) {return find(x)==find(y);} int size(int x) {return s[find(x)];} int compnents_number(){return cnt;} }; int main(){ cin.tie(0); ios::sync_with_stdio(false); int N,M; cin >> N >> M; vvec C(N); rep(i,N){ int b,c; cin >> b >> c; b--,c--; C[c].push_back(b); } UnionFind uf(M); for(auto& v:C){ for(auto& x:v){ uf.unite(v[0],x); } } cout << M-uf.compnents_number() << "\n"; }