bhupixb

N-Queens problem

Jan 25th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3. #define int unsigned long long
  4. const int N = 50;
  5.  
  6. int MD, OD;
  7. int row, col;
  8. int cnt = 0, n;
  9.  
  10. inline bool val(int r, int c) {
  11. if (MD & (1LL<<(r+c))) return 0;
  12. if (OD & (1LL<<(r-c+n-1))) return 0;
  13. if (row & (1LL<<r)) return 0;
  14. if (col & (1LL<<c)) return 0;
  15. return 1;
  16. }
  17.  
  18. inline void Set(int r, int c) {
  19. row |= (1LL<<r);
  20. col |= (1LL<<c);
  21. MD |= (1LL<<(r+c));
  22. OD |= (1LL<<(r-c+n-1));
  23. }
  24.  
  25. inline void reset(int r, int c) {
  26. row -= (1LL<<r);
  27. col -= (1LL<<c);
  28. MD -= (1LL<<(r+c));
  29. OD -= (1LL<<(r-c+n-1));
  30. }
  31.  
  32. int ans = 0;
  33.  
  34. void go(int curCol) {
  35. ++cnt;
  36. if (curCol == n) {
  37. cout << "Found\n";
  38. ++ans;
  39. exit(0);
  40. return;
  41. }
  42. for (int r = 0; r < n; ++r) {
  43. if (val(r, curCol)) {
  44. Set(r, curCol);
  45. go(curCol+1);
  46. reset(r, curCol);
  47. }
  48. }
  49. }
  50.  
  51. signed main() {
  52. n = 30;
  53. cin >> n;
  54. go(0);
  55. cout << ans;
  56. }
Add Comment
Please, Sign In to add comment