#include <bits/stdc++.h>
using namespace std;
const double PI = 3.1415926535897932384626433;
struct Dsu {
  vector<int> p;
  Dsu(int size) {
    p.resize(size);
    for (int i = 0; i < size; i++) p[i] = i;
  }
  int find_set(int v) {
    if (v == p[v]) return v;
    return p[v] = find_set(p[v]);
  }
  void make_set(int v) { p[v] = v; }
  void union_sets(int a, int b) {
    a = find_set(a);
    b = find_set(b);
    if (a != b) p[b] = a;
  }
};
void solve() {
  int n;
  cin >> n;
  ;
  vector<int> p(n);
  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
  }
  vector<int> freq(n);
  Dsu dsu(n);
  vector<int> vis(n);
  for (int i = 0; i < n; i++) {
    if (vis[i]) continue;
    freq[i] = 0;
    int next = i;
    do {
      freq[i]++;
      vis[next] = true;
      next = p[next];
      dsu.union_sets(i, next);
    } while (next != i);
  }
  for (int i = 0; i < n; i++) cout << freq[dsu.find_set(i)] << " ";
  cout << endl;
}
int main() {
  cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
  int t;
  cin >> t;
  ;
  while (t--) solve();
}
