全部TLE求助
查看原帖
全部TLE求助
900910
lsrsrl楼主2024/10/19 22:43

CODE

#include <bits/stdc++.h>
using namespace std;

const int N = 510;
const int dx[] = {-1, 0, 0, 1};
const int dy[] = {0, -1, 1, 0};
int n, m, dis[N][N], sx, sy, tx, ty; char s[N][N]; bool vis[N][N];

void dfs(int x, int y, int d) {
    vis[x][y] = true;
    for (int i = 0; i < 4; i++) {
        int nx = x + dx[i], ny = y + dy[i];
        if (1 <= nx && nx <= n && 1 <= ny && ny <= m && !vis[nx][ny] && dis[nx][ny] >= d) dfs(nx, ny, d);
    } 
}
bool check(int d) {
    memset(vis, 0, sizeof(vis));
    dfs(sx, sy, d);
    return vis[tx][ty];
}
const int x = 0x3f;
int main() {
    memset(dis, x, sizeof(dis));
    cin >> n >> m;
    queue<pair<int, int>> q;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) {
            cin >> s[i][j];
            if (s[i][j] == '+') {
                q.push({i, j});
                dis[i][j] = 0;
            }
            if (s[i][j] == 'V') sx = i, sy = j;
            if (s[i][j] == 'J') tx = i, ty = j;
        }
    while (!q.empty()) {
        int ux = q.front().first, uy = q.front().second; q.pop();
        for (int i = 0; i < 4; i++) {
            int nx = ux + dx[i], ny = uy + dy[i];
            if (1 <= nx && nx <= n && 1 <= ny && ny <= m && dis[nx][ny] > dis[ux][uy] + 1) {
                dis[nx][ny] = dis[ux][uy] + 1;
                q.push({nx, ny});
            }
        }
    }
    int L = 0, R = min(dis[sx][sy], dis[tx][ty]), ans = 0;
    while (L <= R) {
        int M = (L + R) >> 2;
        if (check(M)) ans = M, L = M + 1;
        else R = M - 1;
    }
    cout << ans << "\n";
    return 0;
}

2024/10/19 22:43
加载中...