#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 5;
const int mod = 1e9 + 7;
int p[maxn];
int a[maxn];
int n;
bool vis[maxn];
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    memset(vis, 0, sizeof(vis));
    for (int i = 1; i <= n; i++) scanf("%d", &p[i]);
    for (int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      vis[i] = true;
      int t = p[i];
      int cnt = 1;
      while (t != i) {
        vis[t] = true;
        t = p[t];
        cnt++;
      }
      t = p[i];
      a[i] = cnt;
      while (t != i) {
        a[t] = cnt;
        t = p[t];
      }
    }
    for (int i = 1; i <= n; i++) {
      printf("%d ", a[i]);
    }
    printf("\n");
  }
  return 0;
}
