Luogu P1074 靶形数独

深搜+剪枝

  • 深搜每一个点的数值,用一个数组$vis[3][x][id]$,vis第一维表示行/列/块,第二维表示第几行/列块,第三维表示id这个数,有没有被占,保证满足题目要求,每次搜完整个数独的时候,统计一下答案,最终取答案的最大值输出。
  • 一个最优性剪枝就是:因为枚举的顺序对答案没有影响,所以先枚举0最少的行,保证搜索树最小。(但是我没写出来)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// luogu-judger-enable-o2
#include<bits/stdc++.h>
using namespace std;

struct Solution{
int a[15][15], b[15][15], ans;
bool vis[3][15][10], flag;

int getBlock(int x, int y){
return ((y - 1) / 3) * 3 + (x - 1) / 3;
}

int getGrade(int x, int y){
if(x == 1 || y == 1 || x == 9 || y == 9) return 6;
else if(x == 2 || y == 2 || x == 8 || y == 8) return 7;
else if(x == 3 || y == 3 || x == 7 || y == 7) return 8;
else if(x == 4 || y == 4 || x == 6 || y == 6) return 9;
else return 10;
}

int check(){
int res = 0;
for(int i = 1; i <= 9; i++){
for(int j = 1; j <= 9; j++){
res += a[i][j] * getGrade(i, j);
}
}
return res;
}

void dfs(int k){
int x = (k % 9 == 0 ? 9 : k % 9);
int y = ((k - 1) / 9) + 1;
if(k == 82){
flag = 1;
ans = max(check(), ans);
return;
}
if(!a[x][y]){
for(int i = 1; i <= 9; i++){
if(vis[0][x][i] || vis[1][y][i] || vis[2][getBlock(x, y)][i]) continue;
vis[0][x][i] = 1;
vis[1][y][i] = 1;
vis[2][getBlock(x, y)][i] = 1;
a[x][y] = i;
dfs(k + 1);
a[x][y] = 0;
vis[0][x][i] = 0;
vis[1][y][i] = 0;
vis[2][getBlock(x, y)][i] = 0;
}
}
else dfs(k + 1);
}

void Solve(){
flag = 0;
ans = 0;
for(int i = 1; i <= 9; i++){
for(int j = 1; j <= 9; j++){
scanf("%d", &a[i][j]);
if(a[i][j] == 0) continue;
vis[0][i][a[i][j]] = 1;
vis[1][j][a[i][j]] = 1;
vis[2][getBlock(i, j)][a[i][j]] = 1;
}
}
dfs(1);
if(flag) printf("%d\n", ans);
else printf("-1\n");
}
};

int main(){
Solution().Solve();
return 0;
}
# 搜索

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×