Guest User

Untitled

a guest
Jun 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. long gcd(long a, long b) {
  4. return b == 0 ? a : gcd(b, a % b);
  5. }
  6.  
  7. long calcLCM(long a, long b) {
  8. return a * b / gcd(a,b);
  9. }
  10.  
  11. int main() {
  12. #ifndef ONLINE_JUDGE
  13. freopen("input.txt", "rt", stdin);
  14. freopen("output.txt", "wt", stdout);
  15. #endif
  16. std::ios_base::sync_with_stdio(false);
  17. int n, *perm, *used;
  18. std::cin >> n;
  19. perm = new int[n];
  20. used = new int[n];
  21. long lcm = 1;
  22. for(int i = 0; i < n; i ++) {
  23. std::cin >> perm[i];
  24. perm[i]--;
  25. used[i] = 0;
  26. }
  27. int high = 0;
  28. while(high < n) {
  29. int curr = high; bool first = true;
  30. int clen = 0;
  31. while(first || curr != high) {
  32. first = false;
  33. used[curr] = 1;
  34. curr = perm[curr];
  35. clen ++;
  36. }
  37. lcm = calcLCM(lcm, clen);
  38. while(high < n && used[high] == 1) high++;
  39. }
  40. std::cout << lcm;
  41. delete[] perm;
  42. delete[] used;
  43. std::cin >> lcm;
  44. return 0;
  45. }
Add Comment
Please, Sign In to add comment