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