#include <bits/stdc++.h>
using namespace std;
void printv(vector<int> path) {
  for (const auto& i : path) {
    cout << i << ' ';
  }
  cout << endl;
}
int main() {
  int q, i;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    vector<int> v(n);
    for (i = 0; i < n; i++) {
      cin >> v[i];
    }
    vector<int> ans(n, 1);
    vector<int> buffer;
    buffer.push_back(0);
    set<int> visited;
    visited.insert(1);
    int counter = 1;
    int pointer = 0;
    int nn = 0;
    while (visited.size() < n) {
      if (visited.find(v[pointer]) == visited.end()) {
        visited.insert(v[pointer]);
        counter++;
        pointer = v[pointer] - 1;
        buffer.push_back(pointer);
      } else {
        if (counter > 1) {
          for (i = 0; i < buffer.size(); i++) {
            ans[buffer[i]] = counter;
          }
        }
        counter = 1;
        nn++;
        pointer = nn;
        buffer.clear();
        buffer.push_back(pointer);
        visited.insert(pointer + 1);
      }
    }
    for (i = 0; i < buffer.size(); i++) {
      ans[buffer[i]] = counter;
    }
    printv(ans);
  }
  return 0;
}
