#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  int q, n;
  cin >> q;
  while (q--) {
    cin >> n;
    vector<int> a(1 + n), answer(1 + n, 0);
    map<int, unordered_set<int> > m;
    vector<bool> vis(n + 1, false);
    for (int i = 1; i <= n; ++i) {
      cin >> a[i];
    }
    for (int i = 1; i <= n; ++i) {
      if (!vis[i]) {
        int j = i;
        vis[i] = true;
        while (a[j] != i) {
          m[i].insert(j);
          j = a[j];
          vis[j] = true;
        }
        m[i].insert(j);
      }
    }
    for (auto p : m) {
      int temp = p.second.size();
      answer[p.first] = temp;
      for (auto r : p.second) {
        answer[r] = temp;
      }
    }
    for (int i = 1; i <= n; ++i) cout << answer[i] << " ";
    cout << "\n";
  }
  return 0;
}
