题目传送门
本题是一道经典的博弈搜索问题。
思路
一、核心逻辑:由于每轮填入的数字是固定的(必须是剩余数字中最小的),我们只需要枚举这个数字填入哪个空位。
二、搜索策略:使用 DFS 遍历所有可能的填法。
- 先手回合:尝试所有空位,选择使最终得分差最大的方案。
- 后手回合:尝试所有空位,选择使最终得分差最小的方案。
三、终止条件:当没有剩余数字时,计算当前的行乘积和与列乘积和,返回它们的差值。
AC 代码
#include <bits/stdc++.h>
using namespace std;
long long c()
{
long long a[3][3], u[10], r = a[0][0]*a[0][1]*a[0][2] + a[1][0]*a[1][1]*a[1][2] + a[2][0]*a[2][1]*a[2][2], l = a[0][0]*a[1][0]*a[2][0] + a[0][1]*a[1][1]*a[2][1] + a[0][2]*a[1][2]*a[2][2];
return r - l;
}
long long d(long long s)
{
long long n = 0;
for (int i = 1; i <= 9; i++)
{
if (!u[i])
{
n = i;
break;
}
}
if (!n)
{
return c();
}
long long x[10], y[10], t = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (!a[i][j])
{
x[t] = i;
y[t] = j;
t++;
}
}
}
u[n] = 1;
long long res;
if (s % 2 == 0)
{
res = -1000000000000000000LL;
for (int i = 0; i < t; i++)
{
a[x[i]][y[i]] = n;
res = max(res, d(s + 1));
a[x[i]][y[i]] = 0;
}
}
else
{
res = 1000000000000000000LL;
for (int i = 0; i < t; i++)
{
a[x[i]][y[i]] = n;
res = min(res, d(s + 1));
a[x[i]][y[i]] = 0;
}
}
u[n] = 0;
return res;
}
int main()
{
long long q;
cin >> q;
while (q--)
{
for (int i = 1; i <= 9; i++)
{
u[i] = 0;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> a[i][j];
if (a[i][j])
{
u[a[i][j]] = 1;
}
}
}
long long f = d(0);
if (f > 0)
{
cout << "first" << endl;
}
else if (f < 0)
{
cout << "second" << endl;
}
else
{
cout << "tie" << endl;
}
}
return 0;
}最后,求求管理员大大给过吧!