YauhenMardan

sda

Jun 3rd, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. void swap(int *a, int i, int j)
  5. {
  6. int s = a[i];
  7. a[i] = a[j];
  8. a[j] = s;
  9. }
  10. bool NextSet(int *a, int n)
  11. {
  12. int j = n - 2;
  13. while (j != -1 && a[j] >= a[j + 1]) j--;
  14. if (j == -1)
  15. return false; // больше перестановок нет
  16. int k = n - 1;
  17. while (a[j] >= a[k]) k--;
  18. swap(a, j, k);
  19. int l = j + 1, r = n - 1; // сортируем оставшуюся часть последовательности
  20. while (l<r)
  21. swap(a, l++, r--);
  22. return true;
  23. }
  24. void Print(int *a, int n) // вывод перестановки
  25. {
  26. bool ff = 1;
  27. for (int i = 0; i < n - 1; i++)
  28. {
  29. if (a[i + 1] == (a[i] + 1))
  30. {
  31. ff=0;
  32. }
  33.  
  34. }
  35. if (ff)
  36. {
  37. static int num = 1; // номер перестановки
  38. cout.width(3); // ширина поля вывода номера перестановки
  39. cout << num++ << ": ";
  40. for (int i = 0; i < n; i++)
  41. cout << a[i] << " ";
  42. cout << endl;
  43. }
  44. }
  45. int main()
  46. {
  47. int n, *a;
  48. cout << "N = ";
  49. cin >> n;
  50. a = new int[n];
  51. for (int i = 0; i < n; i++)
  52. a[i] = i + 1;
  53. Print(a, n);
  54. while (NextSet(a, n))
  55. {
  56.  
  57. Print(a, n);
  58. }
  59.  
  60. system("pause");
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment