Advertisement
MiinaMagdy

524 - Prime Ring Problem

May 7th, 2024
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. /*
  2. +---------------------------------------------+
  3. |                                             |
  4. |       © 07/05/2024 (22:40) MinaMagdy        |
  5. |                                             |
  6. +---------------------------------------------+
  7. */
  8. #include <bits/stdc++.h>
  9. #include <ext/pb_ds/assoc_container.hpp>
  10. #include <ext/pb_ds/tree_policy.hpp>
  11.  
  12. using namespace std;
  13. using namespace __gnu_pbds;
  14. #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
  15. #define multi_ordered_set tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update>
  16. #define endl "\n"
  17. #define MOD 1000000007
  18. #define INF 2000000000
  19. #define all(s) s.begin(), s.end()
  20. #define rall(s) s.rbegin(), s.rend()
  21. #define sz(x) int(x.size())
  22.  
  23. typedef long long ll;
  24. typedef long double ld;
  25. typedef unsigned long long ull;
  26.  
  27. bool is_prime(int x) {
  28.     if (x < 2) return false;
  29.     for (int i = 2; i * i <= x; i++) {
  30.         if (x % i == 0) return false;
  31.     }
  32.     return true;
  33. }
  34.  
  35. int n;
  36. vector<int> tmp = {1};
  37.  
  38. void backtrack(int mask = 1, int prev = 1) {
  39.     if (mask == (1 << n) - 1) {
  40.         if (is_prime(prev + 1)) {
  41.             for (int i = 0; i < n; i++) {
  42.                 cout << tmp[i] << " \n"[i == n - 1];
  43.             }
  44.         }
  45.         return;
  46.     }
  47.     for (int i = 0; i < n; i++) {
  48.         if (mask & (1 << i)) continue;
  49.         if (is_prime(prev + i + 1)) {
  50.             tmp.push_back(i + 1);
  51.             backtrack(mask | (1 << i), i + 1);
  52.             tmp.pop_back();
  53.         }
  54.     }
  55. }
  56.  
  57. void solve() {
  58.     int idx = 0;
  59.     while (cin >> n) {
  60.         if (idx)
  61.             cout << endl;
  62.         cout << "Case " << ++idx << ":\n";
  63.         backtrack();
  64.     }
  65. }
  66.  
  67. int main(void)
  68. {
  69.     ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  70.     int testcase = 1;
  71.     // cin >> testcase;
  72.     while (testcase--)
  73.         solve();
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement