a53

Descompune_O_Permutare_In__Cicluri

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