fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. long n = scanner.nextLong();
  8. int[] v = new int[(int) n + 1];
  9.  
  10. for (int i = 1; i <= n; i++) {
  11. v[i] = scanner.nextInt();
  12. }
  13.  
  14. Map<Integer, Long> mp = new HashMap<>();
  15. long ans = 0;
  16.  
  17. for (int i = 1; i <= n; i++) {
  18. int key = v[v[v[i]]];
  19. mp.put(key, mp.getOrDefault(key, 0L) + 1);
  20. // ans = Math.max(ans, mp.get(key));
  21. }
  22.  
  23. for (long x : mp.values()) {
  24. ans += (x * (x - 1)) / 2;
  25. }
  26.  
  27. System.out.println(ans);
  28. scanner.close();
  29. }
  30. }
  31.  
Success #stdin #stdout 0.12s 54464KB
stdin
4
4 2 1 2
stdout
6