#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int a[n], b[n];
    memset(b, 0, sizeof(b));
    for (int i = 0; i < n; i++) {
      cin >> a[i];
    }
    for (int i = 0; i < n; i++) {
      if (b[i] == 0) {
        vector<int> v;
        int val = i, co = 0, ini = i;
        do {
          v.push_back(val);
          co++;
          val = a[val] - 1;
        } while ((ini) != val);
        for (int i = 0; i < v.size(); i++) {
          b[val] = co;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      cout << b[i] << " ";
    }
    cout << endl;
  }
}
