#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  for (int qq = 0; qq < q; qq++) {
    int n;
    cin >> n;
    int kids[200001];
    int perkids[200001];
    for (int i = 1; i <= n; i++) {
      kids[i] = 0;
      cin >> perkids[i];
    }
    for (int i = 1; i <= n; i++) {
      if (kids[i] == 0) {
        int kniga = i, cnt = 0;
        queue<int> k;
        do {
          cnt++;
          kniga = perkids[kniga];
          k.push(kniga);
        } while (kniga != i);
        while (!k.empty()) {
          int ii = k.front();
          k.pop();
          kids[ii] = cnt;
        }
      }
      cout << kids[i] << " ";
    }
    cout << endl;
  }
  return 0;
}
