Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- long gcd(long a, long b) {
- return b == 0 ? a : gcd(b, a % b);
- }
- long calcLCM(long a, long b) {
- return a * b / gcd(a,b);
- }
- int main() {
- int n, *perm, *used;
- std::cin >> n;
- perm = new int[n];
- used = new int[n];
- long lcm = 1;
- for(int i = 0; i < n; i ++) {
- std::cin >> perm[i];
- perm[i]--;
- used[i] = 0;
- }
- int high = 0;
- while(high < n) {
- int curr = high; bool first = true;
- int clen = 0;
- while(first || curr != high) {
- first = false;
- used[curr] = 1;
- curr = perm[curr];
- clen ++;
- }
- lcm = calcLCM(lcm, clen);
- while(high < n && used[high] == 1) high++;
- }
- std::cout << lcm;
- delete[] perm;
- delete[] used;
- return 0;
- }
Add Comment
Please, Sign In to add comment