#include <bits/stdc++.h>
using namespace std;
int q, n, a[200001], b[200001], nrNd;
vector<int> path;
void DFS(int nod) {
  int nextNod = 0;
  ++nrNd;
  path.push_back(nod);
  if (a[nod] != -1) {
    nextNod = a[nod];
    a[nod] = -1;
    DFS(nextNod);
  }
}
int main() {
  cin >> q;
  while (q--) {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= n; i++) {
      if (!path.empty()) path.clear();
      if (a[i] != -1) {
        nrNd = -1;
        DFS(i);
        int len = path.size();
        for (int i = 0; i < len; i++) {
          b[path[i]] = nrNd;
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << b[i] << ' ';
    }
    cout << endl;
  }
  return 0;
}
