#include <bits/stdc++.h>
using namespace std;
int n, p[200005];
int ans[200005];
queue<int> q;
int main() {
  int Q;
  cin >> Q;
  while (Q--) {
    memset(ans, 0, sizeof(ans));
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> p[i];
    for (int i = 1; i <= n; i++) {
      if (ans[i]) continue;
      int step = 1;
      q.push(i);
      for (int j = p[i]; j != i; j = p[j]) {
        q.push(j);
        step++;
      }
      while (!q.empty()) {
        ans[q.front()] = step;
        q.pop();
      }
    }
    for (int i = 1; i <= n; i++) cout << ans[i] << ' ';
    cout << endl;
  }
  return 0;
}
