#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int T = 1;
  cin >> T;
  while (T--) {
    long long int n;
    cin >> n;
    vector<long long int> v(n + 1);
    for (long long int i = 1; i <= n; i++) cin >> v[i];
    vector<vector<long long int>> a;
    bool vis[n + 1];
    memset(vis, false, sizeof vis);
    for (long long int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      long long int u = i;
      vector<long long int> h;
      h.push_back(v[i]);
      vis[i] = true;
      while (u != v[u]) {
        u = v[u];
        if (vis[u]) break;
        vis[u] = true;
        h.push_back(v[u]);
      }
      a.push_back(h);
    }
    vector<long long int> ans(n + 1);
    for (auto d : a) {
      for (auto f : d) ans[f] = d.size();
    }
    for (long long int i = 1; i <= n; i++) cout << ans[i] << " ";
    cout << "\n";
  }
}
