#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int a[n + 1];
    for (int i = 0; i < n; i++) {
      cin >> a[i + 1];
    }
    int ans[n + 1];
    set<int> m;
    for (int i = 1; i <= n; i++) {
      if (m.find(i) != m.end()) {
        continue;
      }
      vector<int> inds;
      int ind = i;
      int nex_ind_to_vis = a[ind];
      int cycle = 0;
      while (ind != nex_ind_to_vis) {
        inds.push_back(nex_ind_to_vis);
        m.insert(nex_ind_to_vis);
        nex_ind_to_vis = a[nex_ind_to_vis];
        cycle++;
      }
      inds.push_back(ind);
      m.insert(ind);
      for (int j = 0; j < inds.size(); j++) {
        ans[inds[j]] = cycle + 1;
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << ans[i] << " ";
    }
    cout << endl;
  }
  return 0;
}
