E
meda
c_cpp
10 months ago
901 B
15
Indexable
#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
template<class T>
void printff(vector<T>& v) {
for (auto k : v) cout << k << " ";
cout << endl;
}
void SOLVE() {
int n, m; cin >> n >> m;
vector<vector<int>> graph(n + 1);
vector<bool> visited(n + 1);
for(int i = 0, u, v; i < m; i++){
cin >> u >> v;
graph[v].push_back(u);
graph[u].push_back(v);
}
function<void(int)> dfs =[&] (int node){
visited[node] = true;
for(auto child : graph[node]){
if(!visited[child]) dfs(child);
}
};
int counter = 0;
for(int i = 1; i <= n; i++){
if(!visited[i]){
dfs(i);
counter++;
}
}
cout << counter - 1 << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int tc = 1; //cin >> tc;
while(tc--) SOLVE();
return 0;
}Editor is loading...
Leave a Comment