nrk009

DFS

Dec 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 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.  
  18. void dfs(int p)
  19. {
  20.     visit[p]=1;
  21.     for(int i=0;i<v[p].size();i++)
  22.     {
  23.         if(!visit[v[p][i]])
  24.         {
  25.           dfs(v[p][i]);
  26.         }
  27.     }
  28. }
  29. int main()
  30. {
  31.     fast;
  32.     ll n,a,c=0;
  33.     cin>>n;
  34.     for(int i=1;i<=n;i++){
  35.     cin>>a;
  36.     v[i].pb(a);
  37.     v[a].pb(i);
  38.     }
  39.     for(int i=1;i<=n;i++)
  40.     {
  41.         if(!visit[i]){
  42.             dfs(i);
  43.         c++;
  44.         }
  45.     }
  46.     cout<<c;
  47.     return 0;
  48. }
Add Comment
Please, Sign In to add comment