1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 1 0 0 0 0 * 0 0 0 0 0 这组数据的答案明显是1 但是我尝试了几份题解代码发现都是输出-1,原因就是估价函数的返回值在这组数据中为2,因为有两个不匹配的位置,但明显这一步是可以修正2个位置的。 我有两个问题 1、是否这里的估价函数定义有误?一次操作最多可以修复两个位置?,估价函数的返回值应设为(ans+1)/2? (3个位置至少需要2次操作) 2、在部分题解中为什么是swap后再判断f()+depth与maxdepth的关系?此时swap了不应该已经操作了一次depth已经+1了吗 下面是我的修改的代码,但依然会T 请求大佬解决我发问题!!!!
#include "bits/stdc++.h"
#define int long long
#define ull unsigned long long
#define double long double
#define PII pair<int,int>
#define TIII tuple<int,int,int>
#define LL __int128
#define eps 1e-6
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
constexpr int N = 2e5 + 10, mod = 1e9 + 7, inf = 1e18;
int n, m;
const vector<vector<int>> goal = {{0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1},
{0, 0, 1, 1, 1, 1},
{0, 0, 0, 2, 1, 1},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0}};
const vector<PII > dir = {{1, 2},
{1, -2},
{-1, 2},
{-1, -2},
{2, 1},
{2, -1},
{-2, 1},
{-2, -1}};
void solve()
{
vector g(6, vector(6, 0));
int x, y;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
char c;
cin >> c;
if (c == '*')
{
x = i, y = j;
g[i][j] = 2;
}
else g[i][j] = c - '0';
}
}
auto f = [&]()
{
int ans = 0;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
if (goal[i][j] != g[i][j]) ans++;
}
}
return (ans + 1) / 2;
};
function<bool(int, int, int, int)> dfs = [&](int x, int y, int depth, int maxdep) -> bool
{
if (f() + depth > maxdep) return false;
if (f() == 0) return true;
for (auto [dx, dy]: dir)
{
int a = x + dx, b = y + dy;
if (a > 5 || a < 1 || b > 5 || b < 1) continue;
swap(g[x][y], g[a][b]);
if (dfs(a, b, depth + 1, maxdep)) return true;
swap(g[x][y], g[a][b]);
}
return false;
};
for (int i = 0; i <= 15; i++)
{
if (dfs(x, y, 0, i))
{
cout << i << endl;
return;
}
}
cout << -1 << endl;
}
signed main()
{
std::ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
freopen("in.txt", "rt", stdin);
freopen("out.txt", "wt", stdout);
int Cases = 1;
cin >> Cases;
while (Cases--)
{
solve();
}
return 0;
}