fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n; cin >> n;
  6. vector<int> arr(n+1);
  7.  
  8. for(int i = 1; i <= n; i++)
  9. cin >> arr[i];
  10.  
  11. unordered_map<int,int> hash;
  12. int cnt = 0;
  13. for(int i = 1; i <= n; i++){
  14. if(arr[i] > n)
  15. continue;
  16.  
  17. int req = arr[arr[arr[i]]];
  18. if(hash.find(req) != hash.end())
  19. cnt += hash[req];
  20.  
  21. hash[arr[arr[arr[i]]]]++;
  22. }
  23. cout << cnt;
  24. return 0;
  25. }
Success #stdin #stdout 0s 5316KB
stdin
4
4 2 1 2
stdout
6