POJ 3278: Catch the Cow(我的第一道广搜...)

大致题意:
farmer John要去抓逃跑的牛,牛懒得跑了,停在位置k(这是个整数),FJ处在位置n(也是个整数)处,他可以通过三种方法变换位置:1)n+1,2)n-1,3)n*2,问最少需要几步可以达到k。
思路分析:(详见注释)
广搜。 定义数组s[N],v[N]分别记 到i位置的最少步数s[i],和是否访问过这个位置的标记v[i]. 写一个广搜的函数,把每次的位置入队。当队列不为空时,更新队头元素(所表示的位置)的s[i],v[i](v变为1,表示现已访问)。每次向三个方向搜索,满足条件的话就输出此时步数,否则向后继续执行同样搜索。

都说这是广搜基础题自己的广搜第一题.............

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;

const int N=100005;
int s[N],v[N]; //number of steps,whether had been visited(0 no/ 1 yes)
int n,k,head,next;
queue<int> q;

int bfs()
{
int i;
q.push(n); //push the begin node into the queue
s[n]=0; //initial step number is 0
v[n]=1; //mark for visited
while(!q.empty()) //while q isn't empty
{
head=q.front(); //get the head of the queue
q.pop(); //pop the head of the queue
for(i=0;i<3;i++)//searh in 3 directions
{
if(i==0)
next=head-1;
else if(i==1)
next=head+1;
else
next=2*head;
if(next>N||next<0) //estimate whether slop over,if so,don't concern it
continue;
if(!v[next]){
q.push(next); //push the node into queue
s[next]=s[head]+1; //mark for visited
v[next]=1;
}
if(next==k) //find the goal, then quit
return s[next];
}
}
return -1;
}
int main()
{
memset(v,0,sizeof(v));
scanf("%d%d",&n,&k);
if(n>=k)
printf("%d",n-k);
else
printf("%d\n",bfs());
return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值