#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int q, n, x, c, c2 = 0, y;
  cin >> q;
  while (q--) {
    cin >> n;
    vector<long long int> v(n + 1);
    vector<long long int> v1(n + 1, 0), v2(n + 1);
    c = 1;
    for (long long int i = 1; i <= n; ++i) cin >> v[i];
    c = 1;
    for (long long int i = 1; i <= n; ++i) {
      if (v1[i] == 0) {
        v1[i] = c;
        x = v[i];
        while (1) {
          ++c2;
          if (v1[x] != 0) break;
          v1[x] = c;
          x = v[x];
        }
        v2[c] = c2;
        ++c;
        c2 = 0;
      }
    }
    for (long long int i = 1; i <= n; ++i) {
      cout << v2[v1[i]] << " ";
    }
    cout << endl;
    v.clear();
    v1.clear();
    v2.clear();
  }
}
