You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
686 B
C++

#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 50;
ll a[N];
int C[N];
int main()
{
int T, n;
scanf("%d", &T);
while (T--)
{
memset(C, 0, sizeof C);
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%lld", a + i);
ll ans = 0;
for (int i = 1; i <= n; i++)
{
int cnt = 0;
for (int x = a[i]; !C[x]; x = a[x])
C[x] = true, cnt++;
if (cnt) ans += cnt - 1;
}
printf("%lld\n", ans);
}
return 0;
}