#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > adj(200007);
bool visited[200007];
bool visited2[200007];
int q, n, count1, ans[200007], tmp;
int p[100007];
int dfs(int x) {
  count1 = 1;
  visited[x] = true;
  for (int i = 0; i < adj[x].size(); i++) {
    if (!visited[adj[x][i]]) {
      dfs(adj[x][i]);
      count1++;
    }
  }
  return count1;
}
void dfs2(int x) {
  visited2[x] = true;
  for (int i = 0; i < adj[x].size(); i++) {
    if (!visited2[adj[x][i]]) {
      ans[adj[x][i]] = tmp;
      dfs2(adj[x][i]);
    }
  }
}
int main() {
  cin >> q;
  while (q--) {
    cin >> n;
    for (int i = 0; i < 200007; i++) {
      visited[i] = false;
      visited2[i] = false;
    }
    memset((ans), 0, sizeof((ans)));
    for (int i = 1; i <= 200007; i++) {
      adj[i].clear();
    }
    for (int i = 1; i <= n; i++) {
      cin >> p[i];
      adj[i].push_back(p[i]);
    }
    if (n == 1) {
      cout << 1 << endl;
      continue;
    }
    for (int i = 1; i <= n; i++) {
      if (!visited[i]) {
        ans[i] = dfs(i);
        tmp = ans[i];
        dfs2(i);
      }
      cout << ans[i] << " ";
    }
  }
}
