#include <bits/stdc++.h>
const long long mod = 998244353;
const long long maxn = 1e18 + 7;
using namespace std;
long long power(long long b, long long p) {
  b %= mod;
  long long ans = 1;
  while (p > 0) {
    if (p % 2 == 1) {
      ans *= b;
      ans %= mod;
    }
    b *= b;
    b %= mod;
    p /= 2;
  }
  return ans;
}
bool cstsort(pair<long long, long long> a, pair<long long, long long> b) {
  if (a.first != b.first) {
    return a.first < b.first;
  } else {
    return a.second > b.second;
  }
}
const long long N = 2e5 + 5;
long long parent[N];
long long sizes[N];
void make(long long v) {
  parent[v] = v;
  sizes[v] = 1;
}
long long find_set(long long v) {
  if (v == parent[v]) {
    return v;
  }
  return parent[v] = find_set(parent[v]);
}
long long union_sets(long long a, long long b) {
  a = find_set(a);
  b = find_set(b);
  if (a != b) {
    if (sizes[a] < sizes[b]) swap(a, b);
    parent[b] = a;
    sizes[a] += sizes[b];
    return 0;
  }
  return sizes[a];
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t = 1;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    long long p[n];
    for (long long i = 0; i < n; i++) cin >> p[i];
    for (long long j = 1; j < n + 1; j++) make(j);
    long long a[n + 1];
    for (long long i = 1; i < n + 1; i++) {
      long long b = find_set(i);
      long long c = find_set(p[i - 1]);
      long long d = union_sets(b, c);
      while (d == 0) {
        b = find_set(p[c - 1]);
        c = find_set(p[b - 1]);
        d = union_sets(b, c);
      }
    }
    for (long long i = 1; i < n + 1; i++) {
      long long j = parent[i];
      while (j != parent[j]) {
        j = parent[j];
      }
      parent[i] = j;
    }
    for (long long i = 1; i < n + 1; i++) {
      cout << sizes[parent[i]] << " ";
    }
    cout << endl;
  }
  return 0;
}
