#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<long long> a(n);
    for (int i = 0; i < n; i++) {
      cin >> a[i];
      a[i]--;
    }
    vector<long long> ans(n), used(n, 0);
    for (int i = 0; i < n; i++) {
      if (!used[i]) {
        vector<long long> cur;
        while (!used[i]) {
          cur.push_back(i);
          used[i] = true;
          i = a[i];
        }
        for (auto it : cur) ans[it] = cur.size();
      }
    }
    for (int i = 0; i < n; i++) cout << ans[i] << " ";
    cout << "\n";
  }
  return 0;
}
