#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int X = 0, w = 0;
  char ch = 0;
  while (!isdigit(ch)) {
    w |= ch == '-';
    ch = getchar();
  }
  while (isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
  return w ? -X : X;
}
const int maxn = 2e5 + 10;
int a[maxn];
int ans[maxn], vis[maxn];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i) {
      cin >> a[i];
      vis[i] = 0;
    }
    int cnt = 0;
    for (int i = 1; i <= n; ++i) {
      if (!vis[i]) {
        int step = 1;
        int now = a[i];
        while (now != i) {
          vis[now] = 1;
          now = a[now];
          step++;
        }
        ans[i] = step;
        now = a[i];
        while (now != i) {
          ans[now] = step;
          now = a[now];
        }
      }
    }
    for (int i = 1; i <= n; ++i) cout << ans[i] << " ";
    cout << endl;
  }
  return 0;
}
