#include <bits/stdc++.h>
using namespace std;
int main() {
  cin.tie(0);
  cout.tie(0);
  ios_base::sync_with_stdio(0);
  int q;
  cin >> q;
  for (int i = 0; i < q; ++i) {
    int n;
    cin >> n;
    vector<int> p(n), comp(n);
    for (int j = 0; j < n; ++j) cin >> p[j];
    int cur = 1;
    for (int j = 0; j < n; ++j) {
      if (comp[j]) continue;
      comp[j] = cur;
      int nex = p[j] - 1;
      while (nex != j) {
        comp[nex] = cur;
        nex = p[nex] - 1;
      }
      ++cur;
    }
    vector<int> len(cur);
    for (auto it : comp) ++len[it - 1];
    for (int j = 0; j < n; ++j) cout << len[comp[j] - 1] << ' ';
    cout << endl;
  }
  return 0;
}
