广搜4--一维广搜
huangzhan170 · · 个人记录
课堂笔记
课堂习题
T582141 星际跃迁追踪协议
思路:一维bfs,在三种判断。最后输出step;
#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。
#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
#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 跳跃机器人
#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;
}