#include <bits/stdc++.h>
const long long ansmod = 1e9 + 7;
using namespace std;
long long int power(long long int x, long long int y, long long int push) {
  long long int res = 1;
  x = x % ansmod;
  if (x == 0) return 0;
  while (y > 0) {
    if (y & 1) res = (res * x) % ansmod;
    y = y >> 1;
    x = (x * x) % ansmod;
  }
  return res;
}
long long int modinv(int a, int mod) { return power(a, ansmod - 2, ansmod); }
long long int gcd(long long int a, long long int b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
class Solution {
 public:
  void solve() {
    long long int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) {
      cin >> arr[i];
    }
    vector<int> an(n);
    int pos;
    int ans;
    vector<int> push;
    vector<bool> visited(n);
    for (int i = 0; i < n; i++) {
      visited[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      if (visited[i] == 1) {
        continue;
      }
      pos = arr[i] - 1;
      push.push_back(i);
      ans = 1;
      visited[i] = 1;
      while (pos != i) {
        push.push_back(pos);
        ans++;
        pos = arr[pos] - 1;
      }
      for (auto e : push) {
        an[e] = ans;
      }
      push.clear();
    }
    for (auto x : an) {
      cout << x << " ";
    }
    cout << "\n";
  }
};
int main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  ;
  int t;
  cin >> t;
  while (t--) {
    Solution ob;
    ob.solve();
  }
  return 0;
}
