fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. inline int power(int a, int b) {
  6. int x = 1;
  7. while (b) {
  8. if (b & 1) x *= a;
  9. a *= a;
  10. b >>= 1;
  11. }
  12. return x;
  13. }
  14.  
  15.  
  16. const int M = 1000000007;
  17. const int N = 3e5+9;
  18. const int INF = 2e9+1;
  19. const int LINF = 2000000000000000001;
  20.  
  21. //_ ***************************** START Below *******************************
  22.  
  23. // 1
  24. // 4
  25. // 4 2 1 2
  26.  
  27.  
  28. //* Alternatve way :
  29. //* freqMap = {
  30. //* x -> c1
  31. //* y -> c2
  32. //* ... -> ...
  33. //* }
  34.  
  35. //* Ans = (1 + 2 + 3 + ... c1-1) + (1 + 2+ ... c2-1) + ....
  36. //* ans = c1(c1-1)/2 + c2(c2-1)/2
  37.  
  38. //* This is what we do each time with =>
  39. //* ans += mp[val]
  40. //* map[val]++
  41.  
  42.  
  43. vector<int> a;
  44. void consistency(int n) {
  45.  
  46. unordered_map<int,int> mp;
  47. int ans = 0;
  48.  
  49. for(int i=1; i<=n; i++){
  50. int val = a[a[a[i]]];
  51. if(mp.count(val)){
  52. ans += mp[val];
  53. }
  54.  
  55. mp[val]++;
  56. }
  57.  
  58. cout << ans << endl;
  59.  
  60. }
  61.  
  62. void solve() {
  63.  
  64. int n;
  65. cin >> n;
  66. a.resize(n+1);
  67. for(int i=1; i<=n; i++) cin >> a[i];
  68. consistency(n) ;
  69.  
  70. }
  71.  
  72.  
  73.  
  74.  
  75.  
  76. int32_t main() {
  77. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  78.  
  79. int t = 1;
  80. cin >> t;
  81. while (t--) {
  82. solve();
  83. }
  84.  
  85. return 0;
  86. }
Success #stdin #stdout 0.01s 5260KB
stdin
1
4
4 2 1 2
stdout
6