#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    int p[n + 1];
    bool mark[n + 1];
    int val[n + 1];
    for (int i = 0; i < n + 1; i++) {
      mark[i] = false;
      p[i] = 0;
      val[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      cin >> p[i];
    }
    for (int i = 1; i <= n; i++) {
      if (!mark[i]) {
        vector<int> viz;
        mark[i] = true;
        int cur = p[i];
        int iter = 1;
        viz.push_back(i);
        while (cur != i) {
          viz.push_back(cur);
          mark[cur] = true;
          iter++;
          cur = p[cur];
        }
        for (auto ii : viz) {
          val[ii] = iter;
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << val[i] << " ";
    }
    cout << endl;
  }
}
