Skip to content

Instantly share code, notes, and snippets.

@sunho
Created May 16, 2022 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunho/372f4a55cff8a59ff504d5be382f1e95 to your computer and use it in GitHub Desktop.
Save sunho/372f4a55cff8a59ff504d5be382f1e95 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
struct DSU {
vector<int> e;
int SCC;
DSU(int n) : e(n, -1), SCC(n) {}
bool sameSet(int a, int b) { return find(a) == find(b); }
int size(int x) { return -e[find(x)]; }
int find(int x) { return e[x] < 0 ? x : e[x] = find(e[x]); }
bool join(int a, int b) {
a = find(a), b = find(b);
if (a == b) return false;
if (e[a] > e[b]) swap(a, b);
e[a] += e[b]; e[b] = a;
SCC--;
return true;
}
};
void solve() {
int n,m;
cin >> n >> m;
DSU dsu(n);
for(int i=0;i<m;i++){
int a,b;
cin >> a >> b;
--a,--b;
dsu.join(a,b);
}
cout << dsu.SCC - 1 << "\n";
}
int main() {
solve();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment