#include <bits/stdc++.h>
using namespace std;
const int SZ = 200005;
vector<int> graph[SZ];
int par[SZ];
int dst[SZ];
int tot;
void dfs(int x, int crt) {
  par[x] = crt;
  tot++;
  for (int nxt : graph[x]) {
    if (par[nxt]) continue;
    dfs(nxt, crt);
  }
}
int main(void) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
      graph[i].clear();
      par[i] = 0;
      dst[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      int x;
      cin >> x;
      graph[i].push_back(x);
    }
    int pp = 0;
    for (int i = 1; i <= n; i++) {
      if (par[i]) continue;
      tot = 0;
      dfs(i, ++pp);
      dst[pp] = tot;
    }
    for (int i = 1; i <= n; i++) cout << dst[par[i]] << " ";
    cout << '\n';
  }
  return 0;
}
