来追梦2026春季周五多源BFS+带约束BFS专题总结

· · 个人记录

课堂总结

前言

几乎所有精力用在修改T2上面,结果跟原来的对比了一下,才发现,有“亿”点点“小”错误!!!

新学了一个折叠框的用法,用的有点多,请谅解哟~

T759360 流感传染

就是一个多源bfs,不再过多赘述了哈!具体看代码+注释☟

#include <bits/stdc++.h>
using namespace std;
const int N = 1e2 + 5;
int n, m, ans, dis[N][N];
bool f[N][N]; char a[N][N];
int dx[5] = {0, 0, -1, 1};
int dy[5] = {-1, 1, 0, 0};
struct node{
    int x, y;
};
queue <node> q;
void bfs(){
    while(q.size()){
        int tx = q.front().x;
        int ty = q.front().y;
        q.pop();
        if(dis[tx][ty] == m - 1) return;//m天过去了……
        for(int i = 0; i < 4; i++){
            int nx = tx + dx[i], ny = ty + dy[i];
            if(nx < 1 || nx > n || ny < 1 || ny > n) continue;//边
            if(f[nx][ny] || a[nx][ny] != '.') continue;//来过+可行性
            f[nx][ny] = true, dis[nx][ny] = dis[tx][ty] + 1;//传染!!!
            q.push({nx, ny}), ans++;//入队,然后又多了一个人得流感了!
        }
    }
}
int main(){
    cin >> n;
    memset(dis, -1, sizeof(dis));
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++){
            cin >> a[i][j];
            if(a[i][j] == '@'){
                ans++;//一开始就得了病的人
                dis[i][j] = 0;//第0天传染
                q.push({i, j});//先入对
            }
        }
    cin >> m;
    bfs();
    cout << ans;
    return 0;
}

P4328 [COCI 2006/2007 #1] Slikar

虽说之前做过,但我也不知道哪里错了,仔细比对了之后吗……思路都是对的,具体为什么错先卖个关子。考试的时候辛辛苦苦修改了40分钟还是没能找出来www

错因:

:::warning[仔细比对了之后,发现了以下亿点点“小”问题:]

具体看注释🤦‍

代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 1e2 + 5;
int n, sx, sy, ex, ey;
char a[N][N];
int f[N][N];//记录拐弯次数
int dx[5] = {0, 1, 0, -1};
int dy[5] = {1, 0, -1, 0};
struct node{
    int x, y, fx, step;//结构体中多添增了一个方向,而且这里的step代表拐弯次数
};
void bfs(int sx, int sy, int turn){
    queue <node> q;
    q.push({sx, sy, turn, 0});
    f[sx][sy] = 0;
    while(q.size()){
        node tp = q.front();
        q.pop();
        for(int i = 0; i < 4; i++){
            int nx = tp.x + dx[i], ny = tp.y + dy[i], ns = tp.step;
            if(tp.fx != i) ns++;//方向不一样,多拐弯一次
            if(nx <= 0 || nx > n || ny <= 0 || ny > n) continue;
            if(a[nx][ny] == 'x' || ns > f[nx][ny]) continue;
            f[nx][ny] = ns;
            q.push({nx, ny, i, ns});
        }
    }
}
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(f, 0x3f, sizeof(f));//初始化
    for(int i = 0; i < 4; i++)//每个方向都搜一遍
        bfs(sx, sy, i);
    if(f[ex][ey] == 0x3f3f3f3f) cout << -1;//无法到达
    else cout << f[ex][ey];//能到则输出拐弯次数
    return 0;
}