#include <bits/stdc++.h>
using namespace std;
auto clk = clock();
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cout << fixed << setprecision(8);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    vector<long long int> a;
    a.push_back(-1);
    for (long long int i = 0; i < n; i++) {
      long long int e;
      cin >> e;
      a.push_back(e);
    };
    vector<long long int> mark(n + 1, 0);
    vector<long long int> v(n + 1, 0);
    vector<long long int> v1(n + 1, 0);
    for (int i = 1; i < n + 1; i++) {
      if (mark[i] == 0) {
        long long int x = i;
        long long int c = 1;
        v[x] = i;
        while (a[x] != i) {
          x = a[x];
          mark[x] = 1;
          c++;
          v[x] = i;
        }
        v1[i] = c;
      }
    }
    for (int i = 1; i < n + 1; i++) {
      cout << v1[v[i]] << " ";
    }
    cout << "\n";
  }
  return 0;
}
