P2226 题解

· · 题解

P2226 [HNOI2001] 遥控赛车比赛 题解

Part0 简化题意

Part1 解法说明

Part2 code

#include <bits/stdc++.h>
// 方向数组,0~3分别对应上右下左
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
using namespace std;
inline int read(){ // 快读
    int f = 1, s = 0;
    char c = getchar();
    while (c < '0' || c > '9'){
        if (c == '-') f = -1;
        c = getchar();
    }
    while ('0' <= c && c <= '9') s = s * 10 + c - '0', c = getchar();
    return f * s;
}
int n, m, X1, Y1, X2, Y2, a[101][101];
int vis[101][101][4];
struct Node{
    int x, y, d, left, step;
  // x&y:坐标
  // d:方向
  // left:转弯操作冷却时间(剩余)
  // step:最短路dis
};
queue<Node> q;
int bfs(int re){
    while (!q.empty()) q.pop();
    memset(vis, 0x3f, sizeof vis);
    if (!a[X1][Y1]) return -1; // 特判起点
    q.push((Node){X1, Y1, 0, re, 0});
    q.push((Node){X1, Y1, 1, re, 0});
    q.push((Node){X1, Y1, 2, re, 0});
    q.push((Node){X1, Y1, 3, re, 0});
    for (int i = 0; i < 4; i++) vis[X1][Y1][i] = re;
    while (!q.empty()){
        Node t = q.front();
        q.pop();
        if (t.x == X2 && t.y == Y2) return t.step;
        for (int i = 0; i < 4; i++){
            int nx = t.x + dx[i], ny = t.y + dy[i];
            if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
            if (!a[nx][ny]) continue;
            if (i == t.d){ // 不转向
                Node v = (Node){nx, ny, i, t.left, t.step + 1};
                if (v.left > 0) v.left--;
                if (v.left >= vis[nx][ny][i]) continue;
                vis[nx][ny][i] = v.left;
                q.push(v);
            }
            else{ // 转向
                if (t.left > 0) continue; // 判断是否可以转弯
                Node v = (Node){nx, ny, i, re - 1, t.step + 1};
                if (v.left >= vis[nx][ny][i]) continue;
                vis[nx][ny][i] = v.left;
                q.push(v);
            }
        }
    }
    return -1; // 无解
}
int main(){
    n = read(), m = read(), X1 = read(), Y1 = read(), X2 = read(), Y2 = read();
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            a[i][j] = read();
    for (int i = 1; i <= 10; i++){
        int ans = bfs(i);
        if (ans != -1) printf("%d %d\n", i, ans);
    }
    return 0; // 完结撒花
}