1 条题解

  • 0
    @ 2026-8-29 21:30:13

    最开始很容易陷入贪心的误区(直接去考虑什么情况下走最优),但我们很容易发现,两个玩家的所有状态 604=1296000060^4 = 12960000是在 1e81e8 极限下的有限状态,故而暴力( BFSBFS 搜索)即可。

    #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;
    }
    
    • 1

    信息

    ID
    3196
    时间
    4000ms
    内存
    1024MiB
    难度
    普及+/提高-
    标签
    递交数
    1
    已通过
    1
    上传者