#include <bits/stdc++.h>
using namespace std;
bool ter(long long a, long long b) { return a > b; }
int main() {
  cin.sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long q;
  cin >> q;
  while (q--) {
    long long n;
    cin >> n;
    vector<pair<long long, long long>> a;
    for (long long j = 0; j < n; j++) {
      pair<long long, long long> temp;
      cin >> temp.first;
      temp.second = -1;
      a.push_back(temp);
    }
    for (long long j = 0; j < n; j++) {
      if (a[j].second == -1) {
        long long z = j, k = 0;
        do {
          k++;
          z = a[z].first - 1;
        } while (z != j);
        do {
          a[z].second = k;
          z = a[z].first - 1;
        } while (z != j);
      }
      if (a[j].second != -1) {
        cout << a[j].second << " ";
      }
    }
    cout << endl;
  }
  return 0;
}
