倒着搜,卡一下时就能过。
/* *\
By
Wu yihao
\* */
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using std::max;
long map[15][15];
const long score[9][9] = {
{6,6,6,6,6,6,6,6,6},
{6,7,7,7,7,7,7,7,6},
{6,7,8,8,8,8,8,7,6},
{6,7,8,9,9,9,8,7,6},
{6,7,8,9,10,9,8,7,6},
{6,7,8,9,9,9,8,7,6},
{6,7,8,8,8,8,8,7,6},
{6,7,7,7,7,7,7,7,6},
{6,6,6,6,6,6,6,6,6}};
long calc()
{
long cnt = 0;
for (long i=0;i<9;i++)
for (long j=0;j<9;j++)
cnt += map[i][j]*score[i][j];
return cnt;
}
long ans = -1;
bool h[15][15];
bool v[15][15];
bool b[15][15][15];
long tt = 0;
void dfs(long x,long y)
{
// --------------------------------- crack on time
tt ++;
if (tt > 15000000)
{
printf("%ld",ans);
exit(0);
}
if (x == -1)
{
long tmp = calc();
ans = max(ans,tmp);
return;
}
// --------------------------------- newx & newy
long nx; long ny;
if (y == 0)
{ nx = x - 1; ny = 8; }
else
{ nx = x; ny = y-1; }
// --------------------------------- filled ones
if (map[x][y] > 0)
{
dfs(nx,ny);
return;
}
// --------------------------------- filled it
for (long i=1;i<10;i++)
{
if (!h[x][i] && !v[y][i] && !b[x/3][y/3][i])
{
h[x][i] = v[y][i] = b[x/3][y/3][i] = true;
map[x][y] = i;
dfs(nx,ny);
map[x][y] = -1;
h[x][i] = v[y][i] = b[x/3][y/3][i] = false;
}
}
}
int main()
{
freopen("sudoku.in","r",stdin);
freopen("sudoku.out","w",stdout);
for (long i=0;i<9;i++)
{
for (long j=0;j<9;j++)
{
do map[i][j] = getchar() - '0';
while (!isdigit(map[i][j]+'0'));
if (map[i][j] == 0)
map[i][j] = -1;
else
{
h[i][map[i][j]] =
v[j][map[i][j]] =
b[i/3][j/3][map[i][j]] = true;
}
}
}
dfs(8,8);
printf("%ld",ans);
return 0;
}