#include <bits/stdc++.h>
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
using namespace std;
const int nax = 1e5 + 5;
bool vis[2 * nax];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int a[n + 2];
    for (int i = 0; i < n; i++) {
      cin >> a[i];
      a[i]--;
    }
    memset(vis, false, sizeof(vis));
    int ans[n + 2];
    for (int i = 0; i < n; i++) {
      if (vis[i] != true) {
        vector<int> belong;
        int p = i;
        while (vis[p] == false) {
          vis[p] = true;
          belong.push_back(p);
          p = a[p];
        }
        for (int j = 0; j < belong.size(); j++) {
          ans[belong[j]] = belong.size();
        }
      }
    }
    for (int i = 0; i < n; i++) {
      cout << ans[i] << " ";
    }
    cout << endl;
  }
  return 0;
}
