Skip to content

Instantly share code, notes, and snippets.

@sunho
Created May 16, 2022 22:03
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/64f24e072474225f243f108fe664f0ce to your computer and use it in GitHub Desktop.
Save sunho/64f24e072474225f243f108fe664f0ce to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
vector<bool> vis;
vector<vector<int>> g;
void dfs(int u) {
if (vis[u]) return;
vis[u] = true;
for(int v : g[u]) {
dfs(v);
}
}
void solve() {
int n,m;
cin >> n >> m;
g.assign(n, {});
for(int i=0;i<m;i++){
int a,b;
cin >> a >> b;
--a,--b;
g[a].push_back(b);
g[b].push_back(a);
}
vis.assign(n, false);
int numComp = 0;
for(int i=0;i<n;i++){
if (!vis[i]) {
dfs(i);
numComp++;
}
}
cout << numComp - 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