#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MOD = 1e9 + 7;
void solve(){
int n;
cin >> n;
vector<int> a(n + 1);
for(int i = 1; i <= n; i++)cin >> a[i];
int ans = 0;
map<int, int> m;
for(int i = 1; i <= n; i++){
m[a[i]] = i;
}
for(int i = 0; i < n; i++){
if(a[i] == i || a[a[i]] == i)continue;
ans++;
m[a[a[i]]] = m[i];
swap(a[m[i]], a[a[i]]);
}
cout << ans << "\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
cin >> t;
for(int i = 1; i <= t; i++){
solve();
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgbGwgbG9uZyBsb25nCgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IE1PRCA9IDFlOSArIDc7Cgp2b2lkIHNvbHZlKCl7CglpbnQgbjsKCWNpbiA+PiBuOwoJCgl2ZWN0b3I8aW50PiBhKG4gKyAxKTsKCQoJZm9yKGludCBpID0gMTsgaSA8PSBuOyBpKyspY2luID4+IGFbaV07CgkKCWludCBhbnMgPSAwOwoJCgkKCW1hcDxpbnQsIGludD4gbTsKCWZvcihpbnQgaSA9IDE7IGkgPD0gbjsgaSsrKXsKCQltW2FbaV1dID0gaTsKCX0KCQoJZm9yKGludCBpID0gMDsgaSA8IG47IGkrKyl7CgkJaWYoYVtpXSA9PSBpIHx8IGFbYVtpXV0gPT0gaSljb250aW51ZTsKCQlhbnMrKzsKCQltW2FbYVtpXV1dID0gbVtpXTsKCQlzd2FwKGFbbVtpXV0sIGFbYVtpXV0pOwoJCQoJCQoJfQoJY291dCA8PCBhbnMgPDwgIlxuIjsKfQoKaW50IG1haW4oKXsKCWlvc19iYXNlOjpzeW5jX3dpdGhfc3RkaW8oZmFsc2UpOwoJY2luLnRpZShudWxscHRyKTsKCQoJaW50IHQgPSAxOwoJY2luID4+IHQ7CgkKCWZvcihpbnQgaSA9IDE7IGkgPD0gdDsgaSsrKXsKCQlzb2x2ZSgpOwoJfQoJcmV0dXJuIDA7Cn0=