#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, j, count, x;
    cin >> n;
    vector<int> v(n + 1);
    vector<int> help(n + 1);
    vector<int> ans(n + 1);
    for (int i = 1; i <= n; ++i) cin >> v[i];
    for (int i = 1; i <= n; ++i) {
      help.clear();
      count = 1;
      if (v[i] != -1) {
        j = i;
        help.push_back(i);
        while (v[j] != i) {
          j = v[j];
          help.push_back(j);
          count++;
        }
        for (int i = 0; i < help.size(); i++) {
          ans[help[i]] = count;
          v[help[i]] = -1;
        }
      }
    }
    for (int i = 1; i <= n; i++) cout << ans[i] << " ";
    cout << "\n";
  }
  return 0;
}
