#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9;
const int mod = inf + 7;
const double eps = 1e-9;
const double pi = acos(-1.0);
int q, n;
int a[200200];
int used[200200];
int ans[200200];
void solve() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    used[i] = 0;
    scanf("%d", a + i);
    a[i]--;
  }
  for (int i = 0; i < n; i++) {
    if (!used[i]) {
      vector<int> c;
      int x = i;
      while (!used[x]) {
        c.push_back(x);
        used[x] = 1;
        x = a[x];
      }
      for (__typeof(c.begin()) it = c.begin(); it != c.end(); it++)
        ans[*it] = c.size();
    }
  }
  for (int i = 0; i < n; i++) {
    if (i) printf(" ");
    printf("%d", ans[i]);
  }
  printf("\n");
}
int main() {
  scanf("%d", &q);
  while (q--) solve();
  return 0;
}
