#include <bits/stdc++.h>
using namespace std;
const long long INFLL = 1e18;
const int MAXN = 3e5;
const long long INF = 1e9;
const long long kek = 998244353;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  ;
  int q;
  cin >> q;
  for (int jj = 0; jj < (q); jj++) {
    int n;
    cin >> n;
    vector<int> p(n);
    for (int j = 0; j < (n); j++) cin >> p[j];
    for (int j = 0; j < (n); j++) p[j]--;
    vector<bool> used(n, false);
    vector<int> ans(n);
    for (int i = 0; i < n; i++) {
      if (used[i] == 0) {
        int cnt = 0;
        vector<int> path;
        int cur = i;
        int nach = i;
        while (cur != nach || cnt == 0) {
          cnt++;
          path.push_back(cur);
          cur = p[cur];
        }
        for (int i = 0; i < path.size(); i++) {
          used[path[i]] = 1;
          ans[path[i]] = cnt;
        }
      }
    }
    for (int i = 0; i < n; i++) cout << ans[i] << " ";
    cout << endl;
  }
}
