#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long q;
  cin >> q;
  while (q--) {
    long long n;
    cin >> n;
    vector<long long> vec(n, 0);
    vector<bool> vis(n, false);
    vector<pair<long long, long long>> p(n);
    for (long long i = 0; i < n; i++) cin >> vec[i];
    for (long long i = 0; i < n; i++) {
      if (!vis[i]) {
        vis[i] = true;
        long long j = vec[i] - 1;
        long long days = 1;
        while (j != i) {
          p[j] = make_pair(1, i);
          vis[j] = true;
          j = vec[j] - 1;
          days++;
        }
        p[i] = make_pair(0, days);
      }
    }
    for (long long i = 0; i < n; i++) {
      if (p[i].first == 0)
        cout << p[i].second << " ";
      else
        cout << p[p[i].second].second << " ";
    }
    cout << endl;
  }
}
