跳到正文

个人记录

BFS 2026/1/27寒——唐果

Har10约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年1月27日
收录
2026年1月27日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

今天主要考察的是一维BFS

P1588 [USACO07OPEN] Catch That Cow S

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

错误原因(0分)
  1. 数组没开双倍。
  2. 搜到小于起点就退出了,导致在终点退后的情况没搜到。

正解

  1. 使用BFS在数轴上搜索。
  2. 注意边界,小于1,大于200000才可以退出。
  3. 数组要开200000,因为可以跳到p×2,也就是2*ex。
C++
#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),

Sramoc(k,m)\text{Sramoc}(k,m) 表示用数字 0,1,2,…,k−10,1,2,\ldots,k-1 组成的正整数中能被 mm 整除的最小数。 如果k=2k=2,m=7m=7,号码就是10011001。

错误原因(20分)
  • 初始的时候,没有pushpush(0)。
  • 最开始的时候,放的是1。(觉得能不用特判)。

正解

  1. 用BFS搜索,将小于k的数一位一位的组合。
  2. 搜索时,记得特判0。
C++
#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;
}
原文