#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int arr[N];
int ans[N];
int vis[N];
int main() {
  int t, n, h, num;
  cin >> t;
  while (t--) {
    memset(vis, 0, sizeof(vis));
    memset(ans, 0, sizeof(ans));
    cin >> n;
    for (int i = 1; i <= n; i++) {
      scanf("%d", arr + i);
    }
    for (int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      h = arr[i];
      num = 1;
      while (h != i) {
        num++;
        vis[h] = 1;
        ans[h] = i;
        h = arr[h];
      }
      ans[h] = num;
    }
    for (int i = 1; i <= n; i++) {
      if (vis[i]) {
        cout << ans[ans[i]] << " ";
      } else {
        cout << ans[i] << " ";
      }
    }
    cout << endl;
  }
  return 0;
}
