BFS 2026/1/27寒——唐果
今天主要考察的是一维BFS
P1588 [USACO07OPEN] Catch That Cow S
起点在X(FJ),重点在Y(牛)。FJ 和牛位于数轴上。可移动至p+1、p-1、p×2。计算 FJ 抓住牛所需的最少移动次数。
错误原因(0分)
- 数组没开双倍。
- 搜到小于起点就退出了,导致在终点退后的情况没搜到。
正解
- 使用BFS在数轴上搜索。
- 注意边界,小于1,大于200000才可以退出。
- 数组要开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分)
- 初始的时候,没有
push (0)。 - 最开始的时候,放的是1。(觉得能不用特判)。
正解
- 用BFS搜索,将小于k的数一位一位的组合。
- 搜索时,记得特判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; }