#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
const int MOD = 1000000007;
const int INF = 1000000001;
const char EOL = '\n';
void solve();
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  solve();
}
void solve() {
  int q;
  cin >> q;
  for (int qq = (0); qq < ((q)); qq++) {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = (0); i < ((n)); i++) {
      cin >> a[i];
      a[i]--;
    }
    vector<int> b(n, 0);
    for (int i = (0); i < ((n)); i++) {
      if (b[i] > 0) {
        cout << b[b[i]];
        if (i == n - 1)
          cout << EOL;
        else
          cout << " ";
        continue;
      }
      int c = a[i];
      b[c] = i;
      int ans = 1;
      while (c != i) {
        c = a[c];
        b[c] = i;
        ans++;
      }
      cout << ans;
      if (i == n - 1)
        cout << EOL;
      else
        cout << " ";
      b[i] = ans;
    }
  }
}
