1 solutions
-
0
#include <bits/stdc++.h> using namespace std; const int N = 15; int col[N], row[N], cell[N]; int a[1 << N], cnt[1 << N]; char str[N][N]; int lowbit(int x) { return x & -x; } int g(int x, int y) { return (x / 3 * 3) + (y / 3); } void file(int x, int y, int val) { col[x] ^= 1 << val; row[y] ^= 1 << val; cell[g(x, y)] ^= 1 << val; } int get(int x, int y) { return col[x] & row[y] & cell[g(x, y)]; } bool dfs(int now) { if(!now) return true; int x, y, tmp = 10; for(int i = 0; i < 9; i ++ ) for(int j = 0; j < 9; j ++ ) if(str[i][j] == '.') { int val = get(i, j); if(!val) return false; // 可行性剪枝 if(cnt[val] < tmp) { tmp = cnt[val]; x = i, y = j; } } for(int i = get(x, y); i; i -= lowbit(i)) { int val = a[lowbit(i)]; str[x][y] = '1' + val; file(x, y, val); if(dfs(now - 1)) return true; file(x, y, val); str[x][y] = '.'; } return false; } int main() { for(int i = 0; i < 1 << 9; i ++ ) for(int j = i; j; j -= lowbit(j)) cnt[i] ++ ; // 当前这个二进制数有几位一 for(int i = 0; i < 9; i ++ ) a[1 << i] = i; // 当前的这个二进制数代表的是哪个数 string s; while(cin >> s, s[0] != 'e') { int now = 0; // 当前可以填几个数 for(int i = 0; i < 9; i ++ ) for(int j = 0; j < 9; j ++ ) str[i][j] = s[i * 9 + j]; for(int i = 0; i < 9; i ++ ) col[i] = row[i] = cell[i] = (1 << 9) - 1; for(int i = 0; i < 9; i ++ ) for(int j = 0; j < 9; j ++ ) if(str[i][j] != '.') file(i, j, str[i][j] - '1'); else now ++ ; dfs(now); for(int i = 0; i < 9; i ++ ) cout << str[i]; puts(""); } return 0; }
- 1
Information
- ID
- 482
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 10
- Tags
- # Submissions
- 1
- Accepted
- 1
- Uploaded By