#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MOD = 1e9 + 7;
void solve(){
int n;
cin >> n;
vector<vector<int>> g(n + 1, vector<int>());
vector<int> in_degree(n + 1, 0);
for(int i = 0; i < n; i++){
int x;
cin >> x;
g[i + 1].push_back(x);
in_degree[x]++;
}
int last = 1;
vector<int> visited(n + 1, 0);
int ans = 2;
int t = 1;
auto dfs = [&](int x, auto && self) -> void {
last = x;
if(visited[x]) {
return;
}
visited[x] = t;
for(auto y: g[x]){
self(y, self);
}
};
vector<int> visited2(n + 1, 0);
auto dfs1 = [&](int x, auto && self) -> void {
if(visited2[x])return;
visited2[x] = 1;
for(auto y: g[x]){
self(y, self);
}
};
for(int i = 1; i <= n; i++){
if(in_degree[i] == 0 && !visited[i]){
dfs(i, dfs);
if(visited[last] == t)dfs1(last, dfs1);
t++;
}
}
visited = visited2;
queue<int> q;
vector<int> times(n + 1, 0);
vector<int> pulses(n + 1, 1);
for(int i = 1; i <= n; i++){
if(in_degree[i] == 0){
times[i] = 1;
q.push(i);
}
}
while(q.size()){
auto x = q.front();
q.pop();
// cout << x << "\n";
for(auto z: g[x]){
in_degree[z]--;
times[z] = max(times[z], max(times[x] + 1, pulses[x] + 1));
pulses[z] += pulses[x];
if(!visited[z] && in_degree[z] == 0)q.push(z);
if(visited[z]){
ans = max(ans, times[z] + 1);
}
}
}
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+PiBuOwoJdmVjdG9yPHZlY3RvcjxpbnQ+PiBnKG4gKyAxLCB2ZWN0b3I8aW50PigpKTsKCXZlY3R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