您的位置:首页 > 其它

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

2015-01-10 21:42 225 查看
大致题意:farmer John要去抓逃跑的牛,牛懒得跑了,停在位置k(这是个整数),FJ处在位置n(也是个整数)处,他可以通过三种方法变换位置:1)n+1,2)n-1,3)n*2,问最少需要几步可以达到k。思路分析:(详见注释)广搜。 定义数组s
,v
分别记 到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
,v
; //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
=0; //initial step number is 0
v
=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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: