#include <bits/stdc++.h>
using namespace std;
bool visit[200100];
int ans[200100];
int arr[200100];
int cnt = 0;
void dfs(int s) {
  cnt++;
  if (visit[s] == false) {
    visit[s] = true;
    dfs(arr[s]);
  }
  ans[s] = cnt;
}
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> arr[i];
    }
    for (int i = 1; i <= n; i++) {
      if (visit[i] == false) {
        cnt = 0;
        dfs(i);
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << ans[i] - 1 << " ";
      visit[i] = false;
      arr[i] = 0;
      ans[i] = 0;
    }
    cout << endl;
  }
  return 0;
}
