#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  long long m;
  cin >> m;
  stack<long long> s;
  while (m--) {
    long long n;
    cin >> n;
    long long a[n], b[n];
    for (long long i = 0; i < n; i++) {
      cin >> a[i];
      a[i]--;
      b[i] = 0;
    }
    for (long long i = 0; i < n; i++) {
      if (b[i] == 0) {
        b[i] = 1;
        long long k = a[i];
        while (k != i) {
          b[k] = 1;
          s.push(k);
          k = a[k];
        }
        s.push(i);
        long long h = s.size();
        while (!s.empty()) {
          b[s.top()] = h;
          s.pop();
        }
      }
    }
    for (long long i = 0; i < n; i++) cout << b[i] << " ";
    cout << endl;
  }
}
