rishiilluri

Untitled

Aug 21st, 2024
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. // Helper function to recursively build permutations with alternating parity
  6. void backtrack(std::vector<int>& perm, std::vector<int>& odds, std::vector<int>& evens, std::vector<std::vector<int>>& results, bool expect_odd) {
  7.     if (perm.size() == odds.size() + evens.size()) {
  8.         results.push_back(perm);
  9.         return;
  10.     }
  11.  
  12.     if (expect_odd) {
  13.         for (size_t i = 0; i < odds.size(); ++i) {
  14.             if (odds[i] != -1) {
  15.                 int num = odds[i];
  16.                 perm.push_back(num);
  17.                 odds[i] = -1;  // Mark as used
  18.                 backtrack(perm, odds, evens, results, !expect_odd);
  19.                 perm.pop_back();
  20.                 odds[i] = num;  // Unmark
  21.             }
  22.         }
  23.     } else {
  24.         for (size_t i = 0; i < evens.size(); ++i) {
  25.             if (evens[i] != -1) {
  26.                 int num = evens[i];
  27.                 perm.push_back(num);
  28.                 evens[i] = -1;  // Mark as used
  29.                 backtrack(perm, odds, evens, results, !expect_odd);
  30.                 perm.pop_back();
  31.                 evens[i] = num;  // Unmark
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. // Main function to initialize and call the recursive generation
  38. void find_alternating_parity_permutations(int n) {
  39.     std::vector<int> odds, evens;
  40.     for (int i = 1; i <= n; ++i) {
  41.         if (i % 2 == 0) {
  42.             evens.push_back(i);
  43.         } else {
  44.             odds.push_back(i);
  45.         }
  46.     }
  47.  
  48.     std::vector<int> perm;
  49.     std::vector<std::vector<int>> results;
  50.  
  51.     backtrack(perm, odds, evens, results, true);
  52.     backtrack(perm, odds, evens, results, false);
  53.  
  54.     std::sort(results.begin(), results.end());
  55.  
  56.     // Print results
  57.     for (const auto& p : results) {
  58.         for (const auto& num : p) {
  59.             std::cout << num << " ";
  60.         }
  61.         std::cout << std::endl;
  62.     }
  63.     return results;
  64. }
  65.  
  66. int main() {
  67.     int n;
  68.     std::cin >> n;
  69.  
  70.     find_alternating_parity_permutations(n);
  71.  
  72.     return 0;
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment