#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  ;
  long long t;
  cin >> t;
  while (t--) {
    long long n, i, j;
    cin >> n;
    vector<long long> p(n + 1);
    for (long long i = 0; i < n; i++) cin >> p[i + 1];
    vector<long long> vis(n + 1, 0), ans(n + 1, 1);
    for (i = 1; i <= n; i++) {
      if (vis[i] == 0) {
        j = i;
        set<long long> s;
        long long x = 0;
        while (s.find(j) == s.end()) {
          s.insert(j);
          vis[j] = 1;
          j = p[j];
          x++;
        }
        for (auto it : s) ans[it] = x;
      }
      cout << ans[i] << ' ';
    }
    cout << endl;
  }
  return 0;
}
