#include #include #include #include #include #include #include #include #include #include #include #define rep(i,n) for(int i = 0; i < n; ++i) #define rep1(i,n) for(int i = 1; i <= n; ++i) using namespace std; templatebool chmax(T &a, const T &b) { if(a < b){ a = b; return 1; } return 0; } templatebool chmin(T &a, const T &b) { if(a > b){ a = b; return 1; } return 0; } template inline int sz(T &a) { return a.size(); } using ll = long long; using ld = long double; using pi = pair; using pl = pair; using vi = vector; using vvi = vector; using vl = vector; using vvl = vector; const int inf = numeric_limits::max(); const ll infll = numeric_limits::max(); struct UFT{ vector par;//親 vector rank;//木の深さ vector size;//木の大きさ int n; UFT(int _n) { n = _n; par.resize(n); rank.assign(n,0); size.assign(n,0); rep(i,n){ par[i] = i; } } //xの根を返す int find(int x) { if(par[x] == x) return x; else return par[x] = find(par[x]); } //x,yを併合 void unite(int x,int y) { x = find(x); y = find(y); if(x == y) return; if(rank[x] < rank[y]){ par[x] = y; size[y] += size[x]; } else{ par[y] = x; size[x] += size[y]; if(rank[x] == rank[y]) rank[x]++; } } //x,yが同じグループにいるかどうかを返す bool same(int x,int y) { return find(x) == find(y); } //xの属する木のサイズを探す int usize(int x) { return size[find(x)]; } }; int main() { int n,m; cin >> n >> m; vvi a(m+1); rep(i,n) { int b,c; cin >> b >> c; a[b].push_back(c); } UFT uf(n+1); rep1(i,m) { if(sz(a[i]) >= 2) { rep1(j,sz(a[i])-1) uf.unite(a[i][0], a[i][j]); } } vi tab(n+1, 0); int res = 0; rep1(i,m) { if(sz(a[i]) == 0) continue; int x = uf.find(a[i][0]); if(tab[x] == 0) tab[x]++; else res++; } cout << res << "\n"; return 0; }