tuki2501

Planets Cycles

Oct 9th, 2020
1,423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // ----------- define --------------
  5. #define int long long
  6. #define vi vector<int>
  7. #define ii pair<int,int>
  8. #define fi first
  9. #define sc second
  10. #define stoi stoll
  11. #define popcnt __builtin_popcount
  12. #define getBit(x, k) ((x >> k) & 1)
  13. #define all(x) (x).begin(),(x).end()
  14. // ---------------------------------
  15.  
  16. void Main() {
  17.   int n; cin >> n;
  18.   vector<int> a(n);
  19.   for (auto &i : a) {
  20.     cin >> i;
  21.     i--;
  22.   }
  23.   vector<int> d(n), res(n);
  24.   for (int i = 0; i < n; i++) {
  25.     if (!d[i]) {
  26.       map<int, int> m;
  27.       vector<int> s;
  28.       int j = i, c = 0;
  29.       while (!d[j]) {
  30.         m[j] = ++c;
  31.         s.push_back(j);
  32.         d[j] = 1;
  33.         j = a[j];
  34.       }
  35.       if (m.count(j)) {
  36.         int r = c - m[j] + 1;
  37.         while (s.size() && m[s.back()] >= m[j]) {
  38.           res[s.back()] = r;
  39.           s.pop_back();
  40.         }
  41.       }
  42.       while (s.size()) {
  43.         res[s.back()] = res[a[s.back()]] + 1;
  44.         s.pop_back();
  45.       }
  46.     }
  47.   }
  48.   for (auto &i : res) cout << i << ' ';
  49.   cout << '\n';
  50. }
  51.  
  52. signed main() {
  53. #ifdef _DEBUG
  54.   // freopen("in" , "r", stdin );
  55.   cerr << "- ---- -- ----- <3\n";
  56. #endif
  57.   cin.tie(0)->sync_with_stdio(0);
  58.   int T = 1;
  59.   // cin >> T;
  60.   while (T--) Main();
  61. }
Advertisement
Add Comment
Please, Sign In to add comment