#include <bits/stdc++.h>
using namespace std;
long long solve(vector<long long> arr, int index, int currIndex) {
  if (currIndex == index) {
    return 1;
  } else {
    return 1 + solve(arr, index, arr[currIndex] - 1);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long testCase;
  cin >> testCase;
  while (testCase--) {
    long long n;
    cin >> n;
    vector<long long> arr;
    for (int i = 0; i < n; i++) {
      long long j;
      cin >> j;
      arr.push_back(j);
    }
    std::vector<int> dp(n, 0);
    for (int i = 0; i < n; i++) {
      if (!dp[i]) {
        long long currentIndex = arr[i] - 1;
        long long ans = 1;
        while (currentIndex != i) {
          ans++;
          currentIndex = arr[currentIndex] - 1;
        }
        long long pos = arr[i] - 1;
        dp[arr[i] - 1] = ans;
        while (pos != i) {
          pos = arr[pos] - 1;
          dp[pos] = ans;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      cout << dp[i] << " ";
    }
    cout << endl;
  }
}
