fork download
  1. #include <bits/stdc++.h>
  2. #define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  3. using namespace std;
  4.  
  5. void dfs(int node,vector<vector<int>> &adj, vector<bool> &vis){
  6. vis[node] = true;
  7. for(auto &n : adj[node]){
  8. if(!vis[n])dfs(n,adj,vis);
  9. }
  10. }
  11. int countComponents(int n, vector<vector<int>>& edges) {
  12. vector<vector<int>> adj(n);
  13. for(auto &ed : edges){
  14. int u = ed[0],v=ed[1];
  15. adj[u].push_back(v);
  16. adj[v].push_back(u);
  17. }
  18. vector<bool> vis(n);
  19. int cnt = 0;
  20. for(int i=0;i<n;i++){
  21. if(!vis[i]){
  22. dfs(i,adj,vis);
  23. cnt++;
  24. }
  25. }
  26. return cnt;
  27. }
  28. void solve() {
  29. int n=3;
  30. vector<vector<int>> edges={{0,1}, {0,2}};
  31. cout<<countComponents(n,edges)<<endl;
  32.  
  33. }
  34.  
  35. int main() {
  36. IOS;
  37. solve();
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
1