Advertisement
Salman_CUET_18

Books exchange

Oct 31st, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6. #ifdef _DEBUG
  7.     freopen("input.txt", "r", stdin);
  8. //  freopen("output.txt", "w", stdout);
  9. #endif
  10.    
  11.     int q;
  12.     cin >> q;
  13.     for (int i = 0; i < q; ++i) {
  14.         int n;
  15.         cin >> n;
  16.         vector<int> p(n);
  17.         for (int j = 0; j < n; ++j) {
  18.             cin >> p[j];
  19.             --p[j];
  20.         }
  21.         vector<int> used(n);
  22.         vector<int> ans(n);
  23.         for (int j = 0; j < n; ++j) {
  24.             if (!used[j]) {
  25.                 vector<int> cur;
  26.                 while (!used[j]) {
  27.                     cur.push_back(j);
  28.                     used[j] = true;
  29.                     j = p[j];
  30.                 }
  31.                 for (auto el : cur) ans[el] = cur.size();
  32.             }
  33.         }
  34.         for (int j = 0; j < n; ++j) cout << ans[j] << " ";
  35.         cout << endl;
  36.     }
  37.    
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement