#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
const int M = 200010;
int Q, n, a[N], cnt;
int head[N], nextt[N], to[N];
int dfn[N], low[N], num, ans[N];
int st[N], top = 0;
inline void add(int x, int y) {
  nextt[++cnt] = head[x];
  to[cnt] = y;
  head[x] = cnt;
}
inline void tarjan(int u) {
  low[u] = dfn[u] = ++num;
  st[++top] = u;
  for (int i = head[u]; i; i = nextt[i]) {
    int v = to[i];
    if (!dfn[v]) {
      tarjan(v);
      low[u] = min(low[u], low[v]);
    } else if (!ans[v]) {
      low[u] = min(low[u], low[v]);
    }
  }
  if (low[u] == dfn[u]) {
    int val[N], tot = 0;
    val[++tot] = u;
    int p = st[top];
    top--;
    while (p != u) {
      val[++tot] = p;
      p = st[top];
      top--;
    }
    for (int i = 1; i <= tot; i++) {
      ans[val[i]] = tot;
    }
  }
}
int main() {
  scanf("%d", &Q);
  while (Q--) {
    top = 0;
    for (int i = 0; i < N; i++) {
      head[i] = ans[i] = dfn[i] = low[i] = 0;
    }
    for (int i = 0; i < M; i++) {
      nextt[i] = to[i] = 0;
    }
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]), add(i, a[i]);
    for (int i = 1; i <= n; i++) {
      if (!ans[i]) tarjan(i);
    }
    for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
    printf("\n");
  }
}
