#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, a;
    cin >> n;
    int arr[n + 1], ans[n + 1], i, cnt;
    for (i = 1; i <= n; i++) {
      cin >> arr[i];
      ans[i] = -1;
    }
    for (i = 1; i <= n; i++) {
      a = arr[i], cnt = 1;
      if (ans[i] == -1) {
        while (a != i) {
          cnt++;
          a = arr[a];
        }
        a = arr[i];
        ans[i] = cnt;
        while (a != i) {
          ans[a] = cnt;
          a = arr[a];
        }
      }
    }
    for (i = 1; i <= n; i++) cout << ans[i] << ' ';
    cout << "\n";
  }
}
