#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    n++;
    vector<int> a(n), ans(n);
    vector<int> vis(n, 0);
    n--;
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
    }
    vector<int> ring;
    for (int i = 1; i <= n; i++) {
      if (vis[i])
        continue;
      else {
        ring.clear();
        int x = i, cnt = 0;
        while (!vis[x]) {
          vis[x] = 1;
          ring.push_back(x);
          x = a[x];
          cnt++;
        }
        for (int y : ring) {
          ans[y] = cnt;
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << ans[i] << " ";
    }
    cout << endl;
  }
}
