nrk009

DFS USING STACK

Dec 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
  4. #define ll long long
  5. #define ld long double
  6. #define pb push_back
  7. #define fe first
  8. #define se second
  9. #define st(x) sort(x.begin(),x.end())
  10. #define rst(x) sort(x.rbegin(),x.rend())
  11. const long double pi = 3.14159265358979323;
  12. const double EPS = 1e-12;
  13. const int N = 1e6 + 5;
  14. const int mod = 1e9 + 7;
  15. vector<ll>v[N];
  16. bool visit[N];
  17. void dfs(int p)
  18. {
  19.     stack<int>s;
  20.     s.push(p);
  21.     visit[p]=1;
  22.     while(!s.empty())
  23.     {
  24.         int x=s.top();
  25.         s.pop();
  26.     for(auto it:v[x])
  27.     {
  28.         if(!visit[it])
  29.         {
  30.          // dfs(v[p][i]);
  31.          visit[it]=1;
  32.          s.push(it);
  33.         }
  34.     }
  35. }
  36. }
  37. int main()
  38. {
  39.     fast;
  40.     ll n,a,c=0;
  41.     cin>>n;
  42.     for(int i=1;i<=n;i++){
  43.     cin>>a;
  44.     v[i].pb(a);
  45.     v[a].pb(i);
  46.     }
  47.     for(int i=1;i<=n;i++)
  48.     {
  49.         if(!visit[i]){
  50.             dfs(i);
  51.         c++;
  52.         }
  53.     }
  54.     cout<<c;
  55.     return 0;
  56. }
Add Comment
Please, Sign In to add comment