#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
const int mod = 1e9 + 7;
int a[maxn], b[maxn], T[maxn];
int vis[maxn];
int ans[maxn];
string s;
int book[maxn];
map<int, int> m;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n;
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
      b[i] = a[i];
      vis[i] = 0;
    }
    sort(b + 1, b + 1 + n);
    for (int i = 1; i <= n; i++) T[b[i]] == i;
    int cnt = 1;
    int ji = 1;
    for (int i = 1; i <= n; i++) {
      int cur = i;
      if (vis[i]) continue;
      if (a[i] == i) {
        m[i] = i;
        ans[i] = 1;
        continue;
      }
      int k = 1;
      while (1) {
        vis[cur] = 1;
        m[cur] = ji;
        int v = a[cur];
        if (vis[v] == 0) k++;
        cur = b[v];
        if (vis[cur]) break;
      }
      book[ji++] = k;
    }
    for (int i = 1; i <= n; i++) {
      if (a[i] == i)
        cout << 1 << " ";
      else
        cout << book[m[i]] << " ";
    }
    cout << endl;
  }
  return 0;
}
