#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    int a[n + 1];
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
    }
    bool v[n + 1];
    int c[n + 1];
    memset(v, false, sizeof(v));
    for (int i = 1; i <= n; i++) {
      if (!v[i]) {
        set<int> s;
        int d = 1;
        s.insert(i);
        v[i] = true;
        int j = i;
        while (a[j] != i) {
          j = a[j];
          v[j] = true;
          s.insert(j);
          d++;
        }
        for (int j : s) {
          c[j] = d;
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << c[i] << " ";
    }
    cout << endl;
  }
}
