题目链接
题意:井字棋,现在放了某些棋子。连成线的时候得分为(空格子数+1)(B赢*-1)问当前棋局中,如果Alice和Bob都按最优策略下棋,最终得分。
思路:典型的min-max对抗搜索,A选取分数最高的一种走法,B选取分数最低的一种走法。
注意的是dfs返回值的初始化问题,min搜索初始值不一定小于0, max初始值不一定大于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
| #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; int graph[5][5]; int judge() { for(int i = 0; i < 3; i++)if(graph[0][i] != 0 && graph[0][i] == graph[1][i] && graph[2][i] == graph[0][i])return graph[0][i]; for(int i = 0; i < 3; i++)if(graph[i][0] != 0 && graph[i][0] == graph[i][1] && graph[i][2] == graph[i][0])return graph[i][0]; if(graph[0][0] != 0 && graph[0][0] == graph[1][1] && graph[0][0] == graph[2][2])return graph[0][0]; if(graph[2][0] != 0 && graph[2][0] == graph[1][1] && graph[2][0] == graph[0][2])return graph[2][0]; return 0; } int getdonow() { int cnt = 0; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(graph[i][j] == 0)cnt++; } } return cnt; } int dfs(int donow) { int person = donow % 2; if(person == 0)person = 2; if(judge() != 0)return person == 2? donow+1 : -donow-1; if(donow == 0)return 0; int retmax = -100, retmin = 100; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(graph[i][j] == 0){ graph[i][j] = person; if(person == 1)retmax = max(retmax, dfs(donow-1)); else retmin = min(retmin, dfs(donow-1)); graph[i][j] = 0; } } } if(person == 1)return retmax; else return retmin; } int main() { int T; int flag; int donow; scanf("%d", &T); while(T--) { memset(graph, 0, sizeof(graph)); for(int i = 0; i < 3; i++) { scanf("%d%d%d", &graph[i][0], &graph[i][1], &graph[i][2]); } donow = getdonow(); int ans = dfs(donow); if(ans > 0 && ans % 2 == 0)ans++; else if(ans < 0 && ans % 2 == 1)ans --; printf("%d\n", ans); } return 0; }
|