Advertisement
fireLUFFY

BFS/CAMP5

Feb 13th, 2022
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int mod=1e9 + 7;
  5.  
  6. main()
  7. {
  8.     int t;cin>>t;
  9.     while(t--){
  10.  
  11.         int n,e;cin>>n>>e;
  12.         int u,v;
  13.         vector<vector<int>>g(n);
  14.         bool vis[n];
  15.         memset(vis,false,sizeof(vis));
  16.  
  17.         for(int i=0;i<e;i++){
  18.             cin>>u>>v;
  19.             g[u].push_back(v);
  20.             g[v].push_back(u);
  21.         }
  22.  
  23.         // for(int i=0;i<n;i++){
  24.         //     cout<<i<<":->";
  25.         //     for(auto it:g[i])
  26.         //         cout<<it<<",";
  27.         //     cout<<endl;
  28.         // }
  29.  
  30.         queue<int>q;
  31.         int ans=0;
  32.  
  33.         for(int i=0;i<n;i++){
  34.             if(vis[i]==false){
  35.                 ans++;
  36.                 q.push(i);
  37.  
  38.                 while(!q.empty()){
  39.                     int node=q.front();
  40.                     q.pop();
  41.                     // cout<<node<<" ";
  42.                     vis[node]=true;
  43.                     for(auto it:g[node]){
  44.                         if(vis[it]==false){
  45.                             q.push(it);
  46.                         }
  47.                     }
  48.                 }
  49.             }
  50.         }
  51.  
  52.         // cerr<<"ans:"<<ans<<endl;
  53.         cout<<ans<<endl;
  54.     }
  55.  
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement