#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
template <typename T>
using v = vector<T>;
template <typename... T>
using tup = tuple<T...>;
const ld PI = 3.1415926535;
v<ll> p;
v<bool> was;
v<ll> cnt;
ll dfs(ll x) {
  if (was[x]) {
    return 0;
  } else {
    was[x] = true;
    return 1 + dfs(p[x]);
  }
}
void setThings(ll x, ll a) {
  if (cnt[x] == -1) {
    cnt[x] = a;
    setThings(p[x], a);
  }
}
void solve() {
  ll n;
  cin >> n;
  p = v<ll>(n);
  for (ll i = 0; i < n; ++i) {
    cin >> p[i];
    --(p[i]);
  }
  was = v<bool>(n, false);
  cnt = v<ll>(n, -1);
  v<ll> x(n, 0);
  for (ll i = 0; i < n; ++i) {
    ll x = dfs(i);
    setThings(i, x);
  }
  for (ll i = 0; i < n; ++i) {
    cout << cnt[i] << ' ';
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  ll t = 1;
  cin >> t;
  for (ll i = 0; i < t; ++i) {
    solve();
  }
}
