#include <bits/stdc++.h>
using namespace std;
const int sizee = 2e5 + 1;
int q, n, arr[sizee];
int check[sizee];
int ans[sizee];
int temp;
void search(int indx, int cnt) {
  if (!check[indx]) {
    check[indx] = temp;
    search(arr[indx], cnt + 1);
  } else {
    ans[temp] = cnt;
  }
}
int main() {
  cin >> q;
  while (q--) {
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> arr[i];
      check[i] = 0;
      ans[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      if (!check[i]) {
        temp = i;
        search(i, 0);
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << ans[check[i]] << " ";
    }
    cout << "\n";
  }
  return 0;
}
