#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    int A[n + 5];
    for (int i = 1; i <= n; i++) scanf("%d", &A[i]);
    bool vis[n + 5];
    memset(vis, false, sizeof vis);
    int Ans[n + 5];
    for (int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      int now = A[i];
      vector<int> vc;
      int day = 0;
      while (true) {
        if (vis[now]) break;
        vis[now] = true;
        vc.push_back(now);
        day++;
        now = A[now];
      }
      for (auto i : vc) {
        Ans[i] = day;
      }
    }
    for (int i = 1; i <= n; i++) {
      printf("%d ", Ans[i]);
    }
    puts("");
  }
  return 0;
}
