#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int h[N], o[N], n, ans, T, u, v, nxt[N], adj[N], sz[N], dfn[N], low[N], ti, i,
    s[N], t, top, tot;
bool ins[N];
inline void fr(int &num) {
  num = 0;
  char c = getchar();
  int p = 1;
  while (c < '0' || c > '9') c == '-' ? p = -1, c = getchar() : c = getchar();
  while (c >= '0' && c <= '9') num = num * 10 + c - '0', c = getchar();
  num *= p;
}
inline void add() { nxt[++t] = h[u], h[u] = t, adj[t] = v; }
inline int Min(register int p, register int q) { return p < q ? p : q; }
inline void scc(register int x) {
  dfn[x] = low[x] = ++ti, s[++top] = x, ins[x] = true;
  for (register int i = h[x], j; i; i = nxt[i])
    !dfn[j = adj[i]] ? scc(j), low[x] = Min(low[x], low[j])
                     : low[x] = Min(low[x], ins[j] ? dfn[j] : low[x]);
  if (dfn[x] == low[x]) {
    register int v;
    ++tot;
    do {
      v = s[top--], ins[v] = false, o[v] = tot, ++sz[tot];
    } while (x != v && top);
  }
}
int main() {
  fr(T);
  while (T--) {
    fr(n);
    for (u = 1; u <= n; ++u) fr(v), add();
    for (register int i = 1; i <= n; ++i)
      if (!dfn[i]) scc(i);
    for (register int i = 1; i <= n; ++i) printf("%d ", sz[o[i]]);
    putchar('\n');
    for (register int i = 1; i <= n; ++i)
      dfn[i] = low[i] = o[i] = sz[i] = h[i] = ins[i] = s[i] = 0;
    t = top = ti = tot = 0;
  }
  return 0;
}
