#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int ans1[N];
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int a[n + 1], visited[n + 1];
    a[0] = 0;
    visited[0] = 0;
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
      visited[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      if (visited[i] == 1) {
        continue;
      }
      int cnt = 0;
      int cur = a[i];
      vector<int> v;
      while (!visited[cur]) {
        v.push_back(cur);
        visited[cur] = 1;
        cnt++;
        cur = a[cur];
      }
      for (int j = 0; j < v.size(); j++) {
        ans1[v[j]] = cnt;
      }
    }
    for (int i = 1; i <= n; i++) {
      cout << ans1[i] << " ";
    }
    cout << endl;
  }
}
