#include <bits/stdc++.h>
using namespace std;
int memo[212345];
int mov = 0;
vector<int> vet;
int main() {
  int Q, N, aux;
  scanf("%d", &Q);
  while (Q--) {
    scanf("%d", &N);
    for (int i = 0; i < N; i++) {
      scanf("%d", &aux);
      vet.push_back(aux - 1);
    }
    for (int i = 0; i < N; i++) {
      if (!memo[i]) {
        vector<int> cicle;
        mov = 1;
        int pos = vet[i];
        while (pos != i) {
          cicle.push_back(pos);
          mov++;
          pos = vet[pos];
        }
        memo[i] = mov;
        for (int i = 0; i < cicle.size(); i++) memo[cicle[i]] = mov;
      }
    }
    for (int i = 0; i < N; i++) {
      if (!i)
        printf("%d", memo[i]);
      else
        printf(" %d", memo[i]);
      memo[i] = 0;
    }
    puts("");
    vet.clear();
  }
  return 0;
}
