#define _CRT_SECURE_NO_WARNINGS #define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING #include 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; }