#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    int arr[n + 1];
    arr[0] = -1;
    for (int i = 1; i <= n; i++) {
      cin >> arr[i];
    }
    int ans[n + 1];
    ans[0] = -1;
    bool found[n + 1];
    for (int i = 1; i <= n; i++) {
      found[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      if (found[i] == 1) {
        continue;
      } else {
        stack<int> s;
        int count = 1;
        int x = i;
        s.push(i);
        while (arr[x] != i) {
          x = arr[x];
          count++;
        }
        while (!s.empty()) {
          found[s.top()] = 1;
          ans[s.top()] = count;
          s.pop();
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << ans[i] << " ";
    }
    cout << endl;
  }
}
