# 二进制优化+dfs

``````#include <iostream>
#include <cstdio>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
char s[100], a[10][10];
int cnt[512], num[512], row[9], col[9], grid[9];

//不加inline竟然过不去。。。。
inline int g(int x, int y) { return (x/3)*3+(y/3); }

inline void flip(int x, int y, int z){
row[x] ^= (1 << z);
col[y] ^= (1 << z);
grid[g(x, y)] ^= (1 << z);
}

bool dfs(int step){
if(step == 0) return true;
int x = -1, y = -1, val = INF;
for(int i = 0; i < 9; i ++){
for(int j = 0; j < 9; j ++){
if(a[i][j] != '.') continue;
int tmp = row[i] & col[j] & grid[g(i, j)];
if(tmp == 0) return false;
if(cnt[tmp] < val) val = cnt[tmp], x = i, y = j;
}
}
int tmp = row[x] & col[y] & grid[g(x, y)];
for(; tmp; tmp -= lowbit(tmp)){
int k = num[lowbit(tmp)];
a[x][y] = (k + 1) + '0';
flip(x, y, k);
if(dfs(step - 1)) return true;
flip(x, y, k);
a[x][y] = '.';
}
return false;
}

int main(){

for(int i = 0; i < (1 << 9); i ++){
for(int j = i; j; j -= lowbit(j)) cnt[i] ++;
}
// 这里注意一下下标，假如我们lowbit之后得到的是1000
// 这时num[1000]=3，1对应的位置是3+1=4
// 也就是说我们实际填的是4
for(int i = 0; i < 9; i ++) num[1 << i] = i;
while(scanf("%s", s) != EOF && s[0] != 'e'){
for(int i = 0; i < 9; i ++){
for(int j = 0; j < 9; j ++) a[i][j] = s[i * 9 + j];
}
for(int i = 0; i < 9; i ++)
row[i] = col[i] = grid[i] = (1 << 9) - 1;
int tot = 0;
for(int i = 0; i < 9; i ++){
for(int j = 0; j < 9; j ++){
if(a[i][j] != '.') flip(i, j, a[i][j] -'0' - 1);
else tot ++;
}
}
dfs(tot);
for(int i = 0; i < 9; i ++){
for(int j = 0; j < 9; j ++) printf("%c", a[i][j]);
}
puts("");
}
return 0;
}``````

0条评论