a53

PermutarePow_CMMDC_ANDR

a53
Sep 28th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <stdlib.h>
  3. #define N 1000005
  4. using namespace std;
  5. ifstream fin("permutarepow.in");
  6. ofstream fout("permutarepow.out");
  7.  
  8. unsigned int n, permutation[N];
  9. unsigned long long maxlen=1;
  10. typedef void(*cyclefn)(const unsigned int *, size_t);
  11. unsigned long long gcd(unsigned long long a, unsigned long long b)
  12. {
  13. if (b == 0)
  14. return a;
  15. return gcd(b, a % b);
  16. }
  17. void permutation_cycles_recursive(const unsigned int *permutation, unsigned int *visited,
  18. unsigned int start, unsigned int current, unsigned int *path,
  19. size_t length, cyclefn fun)
  20. {
  21. visited[current] = 1;
  22. path[length] = current;
  23. if (start == current && length > 0) {
  24. fun(path, length);
  25. }
  26. else {
  27. permutation_cycles_recursive(permutation, visited, start, permutation[current],
  28. path, length + 1, fun);
  29. }
  30. }
  31.  
  32. void permutation_cycles(const unsigned int *permutation, size_t n, cyclefn fun)
  33. {
  34. unsigned int i;
  35. unsigned int *visited = new unsigned int[n];
  36. unsigned int *path = new unsigned int[n];
  37. if (!(visited && path)) {
  38. free(visited);
  39. free(path);
  40. return;
  41. }
  42. for (i = 0; i < n; i++) {
  43. if (!visited[i]) {
  44. permutation_cycles_recursive(permutation, visited, i, i, path, 0, fun);
  45. }
  46. }
  47. free(visited);
  48. free(path);
  49. }
  50.  
  51. void print(const unsigned int *cycle, size_t length)
  52. {
  53. if (length > 1) {
  54. maxlen=(maxlen * length ) / (gcd(maxlen,length));
  55. }
  56. }
  57.  
  58. int main(void)
  59. {
  60. fin>>n;
  61. for(unsigned int i=1;i<=n;i++)
  62. fin>>permutation[i];
  63. n++;
  64. permutation_cycles(permutation, n, print);
  65. fout<<maxlen;
  66. return 0;
  67. }
Add Comment
Please, Sign In to add comment