Dmaxiya

黑白棋 参考代码

Apr 12th, 2025
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 10 + 100;
  6. int maskRow[maxn], maskCol[maxn];
  7. int n = 6;
  8. string str[maxn] = {
  9.     "10.0..",
  10.     "...0..",
  11.     "....00",
  12.     "......",
  13.     "..1..1",
  14.     ".0..1."
  15. };
  16.  
  17. bool judgeCol(int x, int y) {
  18.     for (int i = 0; i < y; ++i) {
  19.         if (maskCol[i] == maskCol[y]) {
  20.             return false;
  21.         }
  22.     }
  23.     return __builtin_popcount(maskCol[y]) == 3;
  24. }
  25.  
  26. bool judgeRow(int x, int y) {
  27.     for (int i = 0; i < x; ++i) {
  28.         if (maskRow[i] == maskRow[x]) {
  29.             return false;
  30.         }
  31.     }
  32.     return __builtin_popcount(maskRow[x]) == 3;
  33. }
  34.  
  35.  
  36. bool dfs(int depth);
  37.  
  38. bool markAndDfs(int x, int y, int mark) {
  39.     char ch = str[x][y];
  40.     str[x][y] = (mark + '0');
  41.     maskRow[x] |= (mark << y);
  42.     maskCol[y] |= (mark << x);
  43.     bool colFlag = (x < 2 ||
  44.                     (__builtin_popcount((maskCol[y] >> (x - 2)) & 7) != 0 &&
  45.                      __builtin_popcount((maskCol[y] >> (x - 2)) & 7) != 3));
  46.     if (x == n - 1) {
  47.         colFlag = colFlag && judgeCol(x, y);
  48.     }
  49.     bool rowFlag = (y < 2 || (
  50.                         __builtin_popcount((maskRow[x] >> (y - 2)) & 7) != 0 &&
  51.                         __builtin_popcount((maskRow[x] >> (y - 2)) & 7) != 3));
  52.     if (y == n - 1) {
  53.         rowFlag = rowFlag && judgeRow(x, y);
  54.     }
  55.     if (colFlag && rowFlag) {
  56.         if (dfs(x * n + y + 1)) {
  57.             return true;
  58.         }
  59.     }
  60.     str[x][y] = ch;
  61.     maskRow[x] &= ~(1 << y);
  62.     maskCol[y] &= ~(1 << x);
  63.     return false;
  64. }
  65.  
  66. bool dfs(int depth) {
  67.     int x = depth / n;
  68.     int y = depth % n;
  69.     if (depth == 36) {
  70.         for (int i = 0; i < n; ++i) {
  71.             cout << str[i] << endl;
  72.         }
  73.         cout << endl;
  74.         return true;
  75.     }
  76.     if (str[x][y] == '.') {
  77.         if (markAndDfs(x, y, 0)) {
  78.             return true;
  79.         }
  80.         if (markAndDfs(x, y, 1)) {
  81.             return true;
  82.         }
  83.         return false;
  84.     }
  85.     if (str[x][y] == '0') {
  86.         return markAndDfs(x, y, 0);
  87.     }
  88.     return markAndDfs(x, y, 1);
  89. }
  90.  
  91. int main() {
  92. #ifdef ExRoc
  93.     freopen("test.txt", "r", stdin);
  94. #endif // ExRoc
  95.  
  96.     dfs(0);
  97.  
  98.     return 0;
  99. }
  100.  
Advertisement
Add Comment
Please, Sign In to add comment