2717 Catch That Cow【bfs】

来源:互联网 发布:购买域名后如何解析 编辑:程序博客网 时间:2024/05/18 15:31

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9226    Accepted Submission(s): 2895


Problem Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
 

Input
Line 1: Two space-separated integers: N and K
 

Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
 

Sample Input
5 17
 

Sample Output
4


第一次用 bfs ,还是在想明白了bfs的工作原理的情况下,才敢用的,其实广搜,我的理解就是把同一个等级的优先考虑完全,如果不满足要求,那么就继续考虑下一层,就比如货架上的商品,分很多层货架,找某个东西的时候,等把某个层面全部搜寻一遍,然后再搜寻下一层,这样就是广搜的搜索模式,如果是把某个小范围的所有层都搜寻一遍,再继续下一小范围,那么这样的搜索就是dfs了.....

学习东西的时候一定要加上自己的理解,只有把所有的知识点都能转化为自己的语言和思想来表达的时候,自己才能算是真正理解了某个知识点,而不是只是单纯的模仿和死记.,个人的学习方法,另外,学东西一定要富有想象力,不能完全按给出的内容学,即使自己想错了,但是总有想对的时候,也许那一个对的念头,就会让自己透彻理解某个知识点,或者给自己带来创新点...

这个题考查的简单的 bfs ,只需要把所有的情况都考虑到,对每一种情况再分别考虑就可以了,但是如果这样三倍三倍的累成下去,会超内存,所以这里用一个数组标记出现过的状态的步数,因为是按时间从小到大一步步处理的,所以后面出现和前面一样的情况,那么到达最后的用时一定不会小于最短的时间了(想想看为什么),然后就是用队列开始拓展状态......

有几个需要注意的地方,一个是数组下标不能为负值,一个是类型出现的标记上,还有一个就是自行车不能后退............



#include<stdio.h>#include<string.h>#include<queue>using namespace std;int n,k,v[1000005];struct po{int time,point;}x,temp;queue<po> q;void bfs(){while(x.point!=k)//判断是否找到所需状态{temp.point=x.point+1;temp.time=x.time+1;//前进一步的状态if(!v[temp.point])//未出现过{q.push(temp);v[temp.point]=1;//用过后标记}temp.point=x.point*2;temp.time=x.time+1;//前进二倍if(temp.point<1000005&&!v[temp.point])//这个是为了防止超出.....{q.push(temp);v[temp.point]=1;}temp.point=x.point-1;temp.time=x.time+1;if(temp.point>=0&&!v[temp.point])//数组下标不能为负值...{q.push(temp);v[temp.point]=1;}q.pop();x=q.front();}}int main(){while(~scanf("%d%d",&n,&k)){int t,m=0;memset(v,0,sizeof(v));//清空标记while(!q.empty())//清空队列{q.pop();}x.point=n;x.time=0;q.push(x);if(n>k){printf("%d\n",n-k);//这个非常坑,自行车不能后退!!!!!continue;}bfs();printf("%d\n",x.time);//返回的就是符合要求的状态所需的时间}return 0;}




0 0
原创粉丝点击