#include <bits/stdc++.h>
using namespace std;
void faster() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
}
const int MAXN = 3e5 + 10;
long long q, n, a[MAXN], b[MAXN], num, t, i;
int main() {
  faster();
  cin >> q;
  while (q--) {
    cin >> n;
    for (i = 1; i <= n; i++) {
      cin >> a[i];
      b[i] = 0;
    }
    for (i = 1; i <= n; i++) {
      t = 0;
      num = i;
      if (b[i] > 0) continue;
      do {
        num = a[num];
        t++;
      } while (num != i);
      do {
        num = a[num];
        b[num] = t;
      } while (num != i);
    }
    for (i = 1; i <= n; i++) {
      cout << b[i] << " ";
    }
    cout << "\n";
  }
}
