2026-5-8 比赛总结

· · 个人记录

比赛传送门:

考试内容: 多源点 bfs,有约束的 bfs

比赛情况

错题总结

T2 - [COCI 2006/2007 #1] Slikar

错误原因

在判断是否可以通过的时候用了 now.step < time[now.x][now.y],正确应该是 now.step <= time[now.x][now.y]。

粗心大意,就不总结这题了哈!

T4 - [USACO07OCT] Obstacle Course S

题意概括

在

### 题目思路 首先,我们不用动脑子就可以想到用 `bfs` 解决。但这道题它求得是最小转换次数,并不是最小步数,所以,我们不能在第一次到达目标位置时就直接返回结果。然后,我们也不能使用标记数组。为什么呢?因为有些时候,你第一次到这个点的时候,**转换次数并不是最优解**,但你把这里标记成了走过,等下一个**更优**的路径经过时,就会判定这个地方已经走过了,就导致了没有更新最优解。 所以,我们的剪枝条件要换成**是否为最优解**,也就是 `now.step < step[now.x][now.y]`。注意:bfs前要提前把 `step` 数组赋值为极大值! 那我们怎么判断它转弯呢?实际上,我们只需在 `Node` 结构体里在添加两个变量 `dx` 和 `dy`,然后在扩展时判断 `_dx != dx[i] && _dy != dy[i]` ,如果是就说明转弯了,需要 `step++`,并更新方向。 最后,我们怎么判断它无解呢?众所周知,无解:就是`bfs` 没有遍历到终点,那 `step` 数组就依旧是初始值,那么你只需判断 `step[sx][sy]` 是否是你设定的极大值即可。 然后这道题就 $\color{green} \texttt{AC}$ 了。 ### 时空复杂度 - 时间复杂度:$O(N^2)

参考代码

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

const int N = 100 + 10;
int n,sx,sy,ex,ey;
char a[N][N];
int step[N][N]; // 第 (x,y) 点最小的转弯次数

// 偏移数组
const int dx[] = {0,1,0,-1};
const int dy[] = {1,0,-1,0};

struct Node{
    int x,y,step,dx,dy;
};

void bfs(int sx,int sy,int dxi,int dyi){
    queue<Node> q;
    step[sx][sy] = 0; // 记得初始化起点!
    q.push({sx,sy,0,dxi,dyi});

    while(!q.empty()){
        Node t = q.front();
        q.pop();

        for(int i = 0;i < 4;i++){
            int nx = t.x + dx[i];
            int ny = t.y + dy[i];
            int nstep = t.step;

            if(dx[i] != t.dx || dy[i] != t.dy) nstep++; // 转弯
            if(nx < 1 || nx > n || ny < 1 || ny > n || a[nx][ny] == 'x') continue;
            if(nstep <= step[nx][ny]){ // 更新答案
                step[nx][ny] = nstep;
                q.push({nx,ny,nstep,dx[i],dy[i]});
            }
        }
    }
    return;
}

int main(){
    cin >> n ;
    for (int i = 1;i <= n;i++){
        for (int j = 1;j <= n;j++){
            cin >> a[i][j];
            if (a[i][j] == 'A') sx = i, sy = j;
            if (a[i][j] == 'B') ex = i, ey = j;
        }
    }

    memset(step,0x3f,sizeof step); // 将所有点最低步数设为0x3f3f3f3f,代表无解
    for(int i = 0;i < 4;i++) bfs(sx,sy,dx[i],dy[i]); // 朝4个方向都进行一次bfs

    if(step[ex][ey] == 0x3f3f3f3f) cout << -1; // 判断是否无解
    else cout << step[ex][ey];

    return 0;
}

Thanks for watching!