Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include <stdlib.h>
- #define N 1000005
- using namespace std;
- ifstream fin("permutarepow.in");
- ofstream fout("permutarepow.out");
- unsigned int n, permutation[N];
- unsigned long long maxlen=1;
- typedef void(*cyclefn)(const unsigned int *, size_t);
- unsigned long long gcd(unsigned long long a, unsigned long long b)
- {
- if (b == 0)
- return a;
- return gcd(b, a % b);
- }
- void permutation_cycles_recursive(const unsigned int *permutation, unsigned int *visited,
- unsigned int start, unsigned int current, unsigned int *path,
- size_t length, cyclefn fun)
- {
- visited[current] = 1;
- path[length] = current;
- if (start == current && length > 0) {
- fun(path, length);
- }
- else {
- permutation_cycles_recursive(permutation, visited, start, permutation[current],
- path, length + 1, fun);
- }
- }
- void permutation_cycles(const unsigned int *permutation, size_t n, cyclefn fun)
- {
- unsigned int i;
- unsigned int *visited = new unsigned int[n];
- unsigned int *path = new unsigned int[n];
- if (!(visited && path)) {
- free(visited);
- free(path);
- return;
- }
- for (i = 0; i < n; i++) {
- if (!visited[i]) {
- permutation_cycles_recursive(permutation, visited, i, i, path, 0, fun);
- }
- }
- free(visited);
- free(path);
- }
- void print(const unsigned int *cycle, size_t length)
- {
- if (length > 1) {
- maxlen=(maxlen * length ) / (gcd(maxlen,length));
- }
- }
- int main(void)
- {
- fin>>n;
- for(unsigned int i=1;i<=n;i++)
- fin>>permutation[i];
- n++;
- permutation_cycles(permutation, n, print);
- fout<<maxlen;
- return 0;
- }
Add Comment
Please, Sign In to add comment