- 题解
同步玩家
- @ 2026-8-29 21:33:17
最开始很容易陷入贪心的误区(直接去考虑什么情况下走最优),但我们很容易发现,两个玩家的所有状态 是在 极限下的有限状态,故而暴力( 搜索)即可。
#include <bits/stdc++.h>
#define int long long
using namespace std;
int T = 1;
const int N = 60 + 1;
const int MoveX[] = {-1, 0, 1, 0}, MoveY[] = {0, 1, 0, -1};
int n;
char graph[N][N];
int dis[N][N][N][N];
vector<pair<int, int>> players;
queue<array<int, 4>> q;
void Bfs() {
int x0 = players[0].first, y0 = players[0].second;
int x1 = players[1].first, y1 = players[1].second;
q.push({x0, y0, x1, y1});
memset(dis, 127, sizeof(dis));
dis[x0][y0][x1][y1] = 0;
while (!q.empty()) {
x0 = q.front()[0], y0 = q.front()[1];
x1 = q.front()[2], y1 = q.front()[3];
q.pop();
if (x0 == x1 && y0 == y1) {
cout << dis[x0][y0][x1][y1];
return;
}
for (int k = 0; k < 4; k++) {
int nx0 = x0 + MoveX[k], ny0 = y0 + MoveY[k];
int nx1 = x1 + MoveX[k], ny1 = y1 + MoveY[k];
if (nx0 < 1 || nx0 > n) nx0 = x0;
if (ny0 < 1 || ny0 > n) ny0 = y0;
if (nx1 < 1 || nx1 > n) nx1 = x1;
if (ny1 < 1 || ny1 > n) ny1 = y1;
if (graph[nx0][ny0] == '#') nx0 = x0, ny0 = y0;
if (graph[nx1][ny1] == '#') nx1 = x1, ny1 = y1;
if (dis[x0][y0][x1][y1] + 1 < dis[nx0][ny0][nx1][ny1]) {
dis[nx0][ny0][nx1][ny1] = dis[x0][y0][x1][y1] + 1;
q.push({nx0, ny0, nx1, ny1});
}
}
}
cout << -1;
}
void Solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> graph[i][j];
if (graph[i][j] == 'P') {
players.push_back({i, j});
//graph[i][j] = '.';
}
}
}
Bfs();
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while (T--) {
Solve();
}
return 0;
}
0 条评论
目前还没有评论...