#include <bits/stdc++.h>
using namespace std;
const long long inf = (1LL << 60) - 1;
const long long mxn = 1e5;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
void solve() {
  long long n;
  cin >> n;
  vector<long long> a(n + 1);
  for (long long i = 1; i <= n; i++) cin >> a[i];
  vector<long long> use(n + 1);
  vector<long long> ans(n + 1);
  for (long long i = 1; i <= n; i++) {
    if (!use[i]) {
      vector<long long> cur;
      while (!use[i]) {
        cur.push_back(i);
        use[i] = 1;
        i = a[i];
      }
      for (auto it : cur) ans[it] = cur.size();
    }
  }
  for (long long i = 1; i <= n; i++) cout << ans[i] << " ";
  cout << "\n";
}
int main() {
  ios::sync_with_stdio(0);
  cout.tie(0);
  ;
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
