#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int q, n, x;
  cin >> q;
  while (q--) {
    cin >> n;
    vector<long long int> ans(n, -1);
    vector<long long int> A;
    for (int i = 0; i < n; i++) {
      cin >> x;
      A.push_back(x - 1);
    }
    for (int i = 0; i < n; i++) {
      if (ans[i] == -1) {
        stack<long long int> s;
        long long int x = A[i];
        s.push(x);
        while (x != i) {
          x = A[x];
          s.push(x);
        }
        long long int sz = s.size();
        while (!s.empty()) {
          ans[s.top()] = sz;
          s.pop();
        }
      }
    }
    for (auto aa : ans) cout << aa << " ";
    cout << endl;
  }
}
