#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, q, i, j, k, l, f = 0, g = 0;
  cin >> q;
  while (q--) {
    f = 0, g = 0;
    cin >> n;
    int arr[n + 1], a[n + 1], b[n + 1];
    for (i = 1; i <= n; i++) {
      a[i] = 0;
      b[i] = 0;
    }
    for (i = 1; i <= n; i++) cin >> arr[i];
    for (i = 1; i <= n; i++) {
      g = 0, f = 0;
      j = i;
      if (a[j] != 0)
        continue;
      else {
        for (k = 1; k <= 2; k++) {
          if (k == 1) {
            while (arr[j] != i) {
              b[g++] = j;
              j = arr[j];
              f++;
            }
          } else {
            for (l = 0; l < g; l++) a[b[l]] = f;
          }
        }
      }
    }
    for (i = 1; i <= n; i++) {
      if (a[i] == 0)
        cout << 1 << " ";
      else
        cout << a[i] + 1 << " ";
    }
    cout << endl;
  }
  return 0;
}
