#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long int t, i, j, n, x, y, m, tmp, ans, sum, mini, k, maxi;
  string s;
  bool flag;
  t = 1;
  cin >> t;
  while (t--) {
    cin >> n;
    map<long long int, long long int> mp;
    for (i = 1; i <= n; i++) cin >> x, mp[x] = i;
    long long int arr[n + 4];
    memset(arr, 0, sizeof(arr));
    for (i = 1; i <= n; i++) {
      if (arr[i]) continue;
      x = i;
      k = 1;
      vector<long long int> v;
      while (true) {
        v.push_back(x);
        if (mp[x] == i) break;
        x = mp[x], k++;
      }
      for (auto z : v) arr[z] = k;
    }
    for (i = 1; i <= n; i++) cout << arr[i] << " ";
    cout << "\n";
  }
}
