#include <bits/stdc++.h>
using namespace std;
int a[200005], ans[200005], vis[200005];
int main() {
  int T;
  cin >> T;
  while (T--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]), vis[i] = 0;
    vector<int> q;
    for (int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      q.clear();
      q.push_back(i);
      int num = 1, p = a[i];
      vis[i] = 1;
      while (p != i) {
        num++;
        vis[p] = 1;
        q.push_back(p);
        p = a[p];
      }
      for (int j = 0; j < q.size(); j++) {
        ans[q[j]] = num;
      }
    }
    for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
    printf("\n");
  }
}
