#include <bits/stdc++.h>
#pragma GCC target("popcnt")
#pragma GCC optimize("Ofast,inline")
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
template <typename T>
T gcd(T x, T y) {
  return y ? gcd(y, x % y) : x;
}
template <typename T>
T lcm(T x, T y) {
  return x / gcd(x, y) * y;
}
template <typename T>
void adm(T &x, T y, T z) {
  x = x + y;
  if (x >= z) x = x - z;
}
template <typename T>
void adj(T &x, T y) {
  if (x >= y || x <= -y) x = x % y;
  if (x < 0) x = x + y;
}
template <typename T>
T qpow(T x, long long y, T z) {
  for (; y; y >>= 1, x = x * x)
    if (y & 1) z = z * x;
  return z;
}
template <typename T>
T mpow(long long w, T x, long long y, T z) {
  for (; y; y >>= 1, x = x * x, x = x % w)
    if (y & 1) z = z * x, z = z % w;
  return z;
}
template <typename T>
T exgcd(T a, T b, T &x, T &y) {
  T t = a;
  b ? (t = exgcd(b, a % b, y, x), y = y - (a / b) * x) : (x = 1, y = 0);
  return t;
}
const double EPS = 1e-7;
const long long MOD = 998244353LL;
const int M = 5000005;
const int N = 300005;
int _, n, t, ans[N], op, ed, d[N];
bool f[N];
vector<int> g[N];
void bfs(int x) {
  for (f[d[op = ed = 1] = x] = true; op <= ed; op++) {
    for (auto &i : g[d[op]])
      if (!f[i]) f[d[++ed] = i] = true;
  }
  for (int i = 1; i <= ed; i++) ans[d[i]] = ed;
}
int main() {
  for (scanf("%d", &_); _; _--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      vector<int>().swap(g[i]);
      f[i] = false;
    }
    for (int i = 1; i <= n; i++) {
      scanf("%d", &t);
      g[i].push_back(t);
    }
    for (int i = 1; i <= n; i++)
      if (!f[i]) bfs(i);
    for (int i = 1; i <= n; i++) printf("%d%c", ans[i], i == n ? '\n' : ' ');
  }
  return 0;
}
