BFS 2026/1/27寒——唐果

· · 个人记录

今天主要考察的是一维BFS

P1588 [USACO07OPEN] Catch That Cow S

起点在X(FJ),重点在Y(牛)。FJ 和牛位于数轴上。可移动至p+1、p-1、p×2。计算 FJ 抓住牛所需的最少移动次数。

错误原因(0分)

  1. 数组没开双倍。
  2. 搜到小于起点就退出了,导致在终点退后的情况没搜到。

    正解

  3. 使用BFS在数轴上搜索。
  4. 注意边界,小于1,大于200000才可以退出。
  5. 数组要开200000,因为可以跳到p×2,也就是2*ex。
    #include <bits/stdc++.h>
    using namespace std;
    int t,sx,ex;
    struct node
    {
     int x,step; 
    };
    queue<node>q;
    bool vis[200005];
    void bfs()
    {
     while(q.size())
     {
         node c=q.front();
         q.pop();
         if(c.x==ex)
         {
             cout << c.step << endl;
             break;
         }
         for(int i=1;i<=3;i++)
         {
             int nx;
             if(i==1) nx=c.x-1;
             if(i==2) nx=c.x+1;
             if(i==3) nx=c.x*2;
             if(nx<1||nx>200000||vis[nx]==1) continue;
             q.push({nx,c.step+1});
             vis[nx]=1;
         }
     }
     for(int i=1;i<=200000;i++) vis[i]=0;
     while(q.size())
     {
         q.pop();
     }
    }
    int main()
    {
     cin >> t;
     while(t--)
     {
         cin >> sx >> ex;
         q.push({sx,0});
         bfs();
     }
     return 0;
    } 

    T725765 Sramoc 问题(EZ)

    有一个号码函数(Sramoc),

    如果$k=2$,$m=7$,号码就是$1001$。 #### 错误原因(20分)
  1. 用BFS搜索,将小于k的数一位一位的组合。
  2. 搜索时,记得特判0。
    #include <bits/stdc++.h>
    using namespace std;
    long long k,m;
    queue<long long>q;
    bool vis[1000005];
    void bfs()
    {
     while(q.size())
     {
         long long x=q.front();
         q.pop();
         if(x%m==0&&x!=0)
         {
             cout << x;
             break;
         }
         for(int i=0;i<k;i++)
         {
             long long nx=x*10+i;
             q.push(nx);
         }
     }
    }
    int main()
    {
     cin >> k >> m;
     q.push(0);
     bfs();
     return 0;
    }