#include <bits/stdc++.h>
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
const int inf = 1e9;
const long long INF = 1e18;
const long long mod = 1e9 + 7;
clock_t time_p = clock();
void ktj() {
  time_p = clock() - time_p;
  cerr << "Time elapsed : " << (float)(time_p) / CLOCKS_PER_SEC << "\n";
}
const int N = 2e5 + 5;
vector<int> g[N];
bool vis[N];
void dfs(int v, int p, int &len, set<int> &s) {
  if (vis[v]) return;
  vis[v] = 1;
  s.insert(v);
  bool ok = 0;
  for (auto c : g[v]) {
    if (c != p) {
      ok = 1;
      dfs(c, v, len, s);
    }
  }
  len++;
}
void solve() {
  long long n, i;
  cin >> n;
  int a[n];
  for (int i = 1; i <= n; i++) {
    g[i].clear();
    vis[i] = 0;
  }
  for (i = 0; i < n; i++) {
    cin >> a[i];
    g[i + 1].push_back(a[i]);
  }
  int ans[n];
  for (i = 1; i < n + 1; i++) {
    if (!vis[i]) {
      set<int> s;
      int len = 0;
      dfs(i, i, len, s);
      for (auto c : s) {
        ans[c - 1] = len;
      }
    }
  }
  for (auto x : ans) cout << x << ' ';
  cout << '\n';
  ;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    solve();
  }
  ktj();
}
