Created
May 16, 2022 22:04
-
-
Save sunho/372f4a55cff8a59ff504d5be382f1e95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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