#include <bits/stdc++.h>
using namespace std;
int dfs(vector<int> arr, vector<int> &visi, vector<bool> &v, int i) {
  int res = 0;
  while (!v[i]) {
    v[i] = true;
    visi.push_back(i);
    i = arr[i] - 1;
    res++;
  }
  return res;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) cin >> arr[i];
    vector<bool> v(n, false);
    vector<int> res(n, 0);
    for (int i = 0; i < n; i++) {
      if (!v[i]) {
        vector<int> visi;
        int val = 0;
        while (!v[i]) {
          v[i] = true;
          visi.push_back(i);
          i = arr[i] - 1;
          val++;
        }
        for (int j = 0; j < visi.size(); j++) {
          res[visi[j]] = val;
        }
      }
    }
    for (int i : res) cout << i << " ";
    cout << endl;
  }
}
