跳到正文

个人记录

广搜4--一维广搜

#SUSPENDED#约 6 分钟
原文
文章信息与版本

文章信息

发布
2025年7月10日
收录
2025年12月12日
更新
2026年11月7日
篇幅
约 6 分钟

版本

  1. v1当前

课堂笔记

笔记

课堂习题

T582141 星际跃迁追踪协议

思路:一维bfs,在三种判断。最后输出step;

C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x,step;
};
int n,m,vis[100005];
queue<node>q;
int main()
{
	cin>>n>>m;
	q.push({n,0});
	vis[n]=1;
	while(q.size()>0)
	{
		node f=q.front();
		q.pop();
		if(f.x==m)
		{
			cout<<f.step;
			return 0;
		}
		int xx=f.x+1;
		if(xx<=1e5&&vis[xx]==0)
		{
			q.push({xx,f.step+1});
			vis[xx]=1;
		}
		xx=f.x-1;
		if(xx>=0&&vis[xx]==0)
		{
			q.push({xx,f.step+1});
			vis[xx]=1;
		}
		xx=f.x*2;
		if(xx<=1e5&&vis[xx]==0)
		{
			q.push({xx,f.step+1});
			vis[xx]=1;
		}
	}
	return 0;
}

T579124 影分身过河

思路:跟上题相似,但得用for循环模拟,最后输出step。

C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x,step;
};
int n,m,vis[100005],a[100005];
queue<node>q;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	q.push({1,0});
	vis[1]=1;
	while(q.size()>0)
	{
		node f=q.front();
		q.pop();
		if(f.x>=n)
		{
			cout<<f.step;
			return 0;
		}
		if(a[f.x]>0)
		{
			for(int i=1;i<=a[f.x];i++)
			{
				int xx=f.x+i;
				if(xx>0&&vis[xx]==0)
				{
					q.push({xx,f.step+1});
					vis[xx]=1;
				}
				
			}	
		}
		else 
		{
			for(int i=1;i<=f.x+a[f.x];i++)
			{
				int xx=i;
				if(xx>0&&vis[xx]==0)
				{
					q.push({xx,f.step+1});
					vis[xx]=1;
				}
				
			}	
		}
	}
	cout<<"-1";
	return 0;
}

家庭作业

P1588 [USACO07OPEN] Catch That Cow S

C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x,step;
};
int n,m,vis[100005];
int main()
{
	ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin>>t; 
    while(t--) 
    {
    	queue<node>q;
    	memset(vis,0,sizeof(vis));
		cin>>n>>m;
		q.push({n,0});
		vis[n]=1;
		while(q.size()>0)
		{
			node f=q.front();
			q.pop();
			if(f.x==m)
			{
				cout<<f.step<<"\n";
				break;
			}
			int xx=f.x+1;
			if(xx<=1e5&&vis[xx]==0)
			{
				q.push({xx,f.step+1});
				vis[xx]=1;
			}
			xx=f.x-1;
			if(xx>=0&&vis[xx]==0)
			{
				q.push({xx,f.step+1});
				vis[xx]=1;
			}
			xx=f.x*2;
			if(xx<=1e5&&vis[xx]==0)
			{
				q.push({xx,f.step+1});
				vis[xx]=1;
			}
		}
	}
	return 0;
}

B3626 跳跃机器人

C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x,step;
};
int m,vis[1000005];
int main()
{
	ios::sync_with_stdio(false);
    cin.tie(nullptr);
	queue<node>q;
	cin>>m;
	if(m==1) 
	{
        cout<<0;
        return 0;
    }
	q.push({1,0});
	vis[1]=1;
	while(q.size())
	{
		node f=q.front();
		q.pop();
		int xx=f.x+1;
		if(xx==m)
		{
			cout<<f.step+1;
			return 0;
		}
		if(xx<=m&&vis[xx]==0)
		{
			q.push({xx,f.step+1});
			vis[xx]=1;
		}
		xx=f.x-1;
		if(xx>=1&&vis[xx]==0)
		{
			q.push({xx,f.step+1});
			vis[xx]=1;
		}
		xx=f.x*2;
		if(xx==m) 
		{
            cout<<f.step+1;
            return 0;
        }
		if(xx<=m&&vis[xx]==0)
		{
			q.push({xx,f.step+1});
			vis[xx]=1;
		}
	}
	return 0;
}
原文