Advertisement
IlidanBabyRage

858.cpp

Jul 25th, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <cstdio>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. const char opened = 2;
  9. const char marked = 1;
  10. const char untouched = 0;
  11.  
  12. int n, tmp, *prev, count;
  13. char *vis;
  14. vector<int> *a;
  15.  
  16. void ds(int k);
  17.  
  18. int main(){
  19.    
  20.     cin >> n;
  21.     a = new vector<int>[n];
  22.     prev = new int[n];
  23.     vis = new char[n];
  24.     count = 0;
  25.  
  26.     for (int i = 0; i < n; i++){
  27.         cin >> tmp;
  28.         a[--tmp].push_back(i);
  29.         prev[i] = tmp;
  30.         vis[i] = untouched;
  31.     }
  32.  
  33.     for (int i = 0; i < n; i++){
  34.         if (vis[i] == opened)
  35.             continue;
  36.         int j = i;
  37.         while (vis[prev[j]] == untouched){
  38.             vis[j] = marked;
  39.             j = prev[j];
  40.         }
  41.         ds(j);
  42.         count++;
  43.     }
  44.  
  45.     cout << count << endl;
  46.  
  47.     delete [] a;
  48.     delete [] vis;
  49.     delete [] prev;
  50.  
  51.     return 0;
  52. }
  53.  
  54. void ds(int k){
  55.     vis[k] = opened;
  56.     for (int i = 0; i < a[k].size(); i++){
  57.         if (vis[a[k][i]] == opened)
  58.             continue;
  59.         ds(a[k][i]);
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement