#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    vector<int> p(n);
    for (int i = 0; i < n; i++) {
      cin >> p[i];
      --p[i];
    }
    vector<int> used(n);
    vector<int> ans(n);
    for (int i = 0; i < n; i++) {
      if (!used[i]) {
        vector<int> cur;
        while (!used[i]) {
          cur.push_back(i);
          used[i] = true;
          i = p[i];
        }
        for (auto x : cur) ans[x] = cur.size();
      }
    }
    for (int j = 0; j < n; j++) cout << ans[j] << " ";
    cout << "\n";
  }
  return 0;
}
