#include <bits/stdc++.h>
using namespace std;
long long x[200200], y[200200];
void solve(long long i) {
  set<long long> s;
  while (s.count(i) == 0) {
    s.insert(i);
    y[i] = 1;
    i = x[i] - 1;
  }
  for (auto l = s.begin(); l != s.end(); l++) {
    x[*l] = s.size();
  }
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long a;
    cin >> a;
    for (int i = 0; i < a; i++) {
      cin >> x[i];
      y[i] = 0;
    }
    long long q = 0;
    for (int i = 0; i < a; i++) {
      if (q >= a) break;
      if (y[i] == 0) solve(i);
    }
    for (int i = 0; i < a; i++) cout << x[i] << ' ';
    cout << endl;
  }
}
