#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n;
  cin >> n;
  vector<int> arr(n);
  for (int i = 0; i < n; i++) {
    int x;
    cin >> x;
    arr[i] = x - 1;
  }
  vector<bool> vis(n);
  vector<int> res(n);
  for (int i = 0; i < n; i++) {
    if (!vis[i]) {
      int temp = i;
      int cnt = 1;
      vector<int> sat;
      while (arr[temp] != i) {
        vis[arr[temp]] = true;
        sat.push_back(arr[temp]);
        temp = arr[temp];
        cnt++;
      }
      sat.push_back(arr[temp]);
      vis[arr[temp]] = true;
      int l = sat.size();
      for (int j = 0; j < l; j++) {
        res[sat[j]] = cnt;
      }
    }
  }
  for (int i = 0; i < n; i++) cout << res[i] << " ";
  cout << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}
