#include <bits/stdc++.h>
using namespace std;
long long int mod(long long int x) { return x % 1000000007; }
long long int power(long long int x, long long int y, long long int p) {
  long long int res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    vector<long long int> arr(n + 1);
    for (long long int i = 1; i <= n; ++i) cin >> arr[i];
    vector<bool> vis(n + 1);
    vector<long long int> ans(n + 1);
    for (long long int i = 1; i <= n; ++i) {
      if (!vis[i]) {
        long long int curr = i;
        long long int co = 0;
        do {
          vis[curr] = true;
          curr = arr[curr];
          ++co;
        } while (curr != i);
        curr = i;
        do {
          ans[curr] = co;
          curr = arr[curr];
        } while (curr != i);
      }
    }
    for (long long int i = 1; i <= n; ++i) cout << ans[i] << " ";
    cout << endl;
  }
}
