#include <bits/stdc++.h>
using namespace std;
int main() {
  stack<int> s;
  int a[200010], T, N, v[200010], k, kk, b[200010];
  cin >> T;
  while (T--) {
    cin >> N;
    memset(v, 0, sizeof(v));
    memset(b, 0, sizeof(b));
    for (int i = 1; i <= N; i++) cin >> a[i];
    for (int i = 1; i <= N; i++) {
      kk = 0;
      k = i;
      while (!v[k]) {
        s.push(k);
        v[k] = 1;
        k = a[k];
        kk++;
      }
      while (!s.empty()) {
        b[s.top()] = kk;
        s.pop();
      }
    }
    for (int i = 1; i <= N - 1; i++) cout << b[i] << " ";
    cout << b[N];
    cout << endl;
  }
  return 0;
}
