#include <bits/stdc++.h>
using namespace std;
const long long MAX = 1e5;
const long long mod = 1000000007;
ostream &operator<<(ostream &os, vector<long long> v) {
  for (auto &ele : v) {
    printf("%lld ", ele);
  }
  return os;
}
class disjoint_set {
 public:
  vector<long long> parent, size;
  long long N;
  disjoint_set(long long n) {
    N = n;
    parent.resize(n + 1);
    size.resize(n + 1, 1);
    iota(parent.begin(), parent.end(), 0);
  }
  long long root(long long i) {
    return (parent[i] == i) ? i : root(parent[parent[i]]);
  }
  bool find(long long i, long long j) { return (root(i) == root(j)); }
  void unite(long long i, long long j) {
    long long u = root(i);
    long long v = root(j);
    if (u != v) {
      N -= 1;
      if (size[u] < size[v]) {
        swap(u, v);
      }
      parent[v] = u;
      size[u] += size[v];
    }
  }
};
void solve() {
  long long N;
  cin >> N;
  disjoint_set dsu(N);
  vector<long long> v(N);
  for (long long i = (0); (1) > 0 ? i < (N) : i >= (N); i += (1)) {
    cin >> v[i];
    v[i] -= 1;
  }
  vector<long long> used(N);
  vector<long long> ans(N);
  for (long long i = (0); (1) > 0 ? i < (N) : i >= (N); i += (1)) {
    if (!used[i]) {
      vector<long long> cur;
      while (!used[i]) {
        cur.push_back(i);
        used[i] = true;
        i = v[i];
      }
      for (auto el : cur) ans[el] = cur.size();
    }
  }
  for (long long i = (0); (1) > 0 ? i < (N) : i >= (N); i += (1)) {
    cout << ans[i] << " ";
  }
  cout << endl;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long tc = 1;
  cin >> tc;
  while (tc--) {
    solve();
  }
  return 0;
}
