#include <bits/stdc++.h>
using namespace std;
using ii = long long;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int q;
  cin >> q;
  for (int it = 0; it < q; ++it) {
    int n;
    cin >> n;
    vector<int> v(n);
    for (int i = 0; i < n; ++i) {
      cin >> v[i];
      v[i]--;
    }
    vector<int> ci(n);
    vector<int> sz(n + 1);
    int c = 0;
    for (int i = 0; i < n; ++i) {
      if (ci[i]) continue;
      c++;
      int it = i;
      int j = 0;
      while (!ci[it]) {
        ci[it] = c;
        it = v[it];
        ++j;
      }
      sz[c] = j;
    }
    for (int i = 0; i < n; ++i) {
      cout << sz[ci[i]] << " ";
    }
    cout << "\n";
  }
}
