#include <bits/stdc++.h>
#pragma gcc optimize("ofast")
using namespace std;
long long modexp(long long a, long long b, long long m) {
  long long r = 1;
  a = a % m;
  while (b > 0) {
    if (b & 1) r = (r * a) % m;
    b = b / 2;
    a = (a * a) % m;
  }
  return r % m;
}
int main() {
  long long q;
  cin >> q;
  while (q--) {
    long long n;
    cin >> n;
    vector<long long> arr(n);
    for (int i = 0; i < n; i++) {
      cin >> arr[i];
      --arr[i];
    }
    vector<bool> vis(n, false);
    vector<long long> ans(n, 0);
    for (long long i = 0; i < n; i++) {
      long long cnt = 0;
      long long pre = i;
      vector<long long> temp;
      while (!vis[pre]) {
        cnt++;
        temp.push_back(pre);
        vis[pre] = true;
        pre = arr[pre];
      }
      for (auto x : temp) ans[x] = cnt;
    }
    for (auto x : ans) cout << x << " ";
    cout << endl;
  }
  return 0;
}
