Advertisement
NS2A2

DFS+BFS

Jul 16th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3.  
  4. using namespace std;
  5.  
  6. const int maxn= 1e5+5;
  7.  
  8. int n,m;
  9. int check[maxn];
  10. vector <int> e[maxn];
  11. stack<int> s;
  12. queue <int> q;
  13. int ans=0;
  14.  
  15. /*void dfs(int x){
  16.     //while(!s.empty()) s.pop();
  17.     s.push(x);
  18.     check[x]=1;
  19.     while(!s.empty()){
  20.         int u=s.top();
  21.         s.pop();
  22.         //cout<<u<<" ";
  23.         for (int v: e[u])
  24.             if (check[v]==0){
  25.                check[v]=1;
  26.                s.push(v);
  27.             }
  28.     }
  29. }*/
  30.  
  31. void bfs(int x)
  32. {
  33.     q.push(x);
  34.     check[x]=1;
  35.     while(!q.empty())
  36.     {
  37.         int u=q.front();
  38.         q.pop();
  39.         //cout<<u<<" ";
  40.         for (int v: e[u])
  41.             if (check[v]==0)
  42.             {
  43.                 check[v]=1;
  44.                 q.push(v);
  45.             }
  46.     }
  47. }
  48.  
  49. int main()
  50. {
  51.     cin>>n>>m;
  52.     for (int i=1; i<=m; i++)
  53.     {
  54.         int u,v;
  55.         cin>>u>>v;
  56.         e[u].push_back(v);
  57.         e[v].push_back(u);
  58.     }
  59.     //dfs(1);
  60.     //bfs(1);
  61.     for (int i=1; i<=n; i++)
  62.     {
  63.         if (check[i]==0)
  64.         {
  65.             ans++;
  66.             dfs(i);
  67.             //bfs(i);
  68.         }
  69.     }
  70.     cout<<ans<<endl;
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement