码迷,mamicode.com
首页 > 其他好文 > 详细

bfs入门

时间:2017-05-24 21:07:35      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:scan   模拟   open   fine   stream   return   mat   head   math   

愉快的开始写一些很水的东西,一直不会bfs很难受,于是今天来颓会bfs

一道满经典的题目——抓住那头牛!openjudge 2971

 

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:

1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?

 

很显然是一个bfs的题, 队列模拟。

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<algorithm>
 6 #define l 100010
 7 using namespace std ;
 8 
 9 bool f;
10 int N , K , i , head , tail=1 , pre[l] , ans , x[l] , X , vis[l] ;//tail表示上一个的head。
11 
12 int main()
13 {
14     int a;
15     scanf("%d%d",&N,&K);
16     if(N==K) printf("0");
17     x[1]=N;//路径坐标(队列编号)
18     vis[N]=1;//是否访问
19     while(head != tail){
20         head ++ ;//光标下移
21         for(int i = 1 ; i <= 3 ; i ++){//这里是三个方向。
22             f = false ;是否能走
23             if(i == 1 && x[head]>=0){
24                 X = x[head]-1; f=true ;//左移
25             }
26             if(i == 2 && x[head]<K){
27                 X = x[head]+1; f=true ;//右移
28             }
29             if(i == 3 && x[head]<K){//整体乘2
30                 X = x[head]*2; f=true ;
31             }
32             if(f && !vis[X]){//能否行走
33                 tail ++ ;
34                 pre[tail]=head ;//祖先的坐标
35                 x[tail]=X;//入队
36                 vis[X]=1;//拜访这一位
37                 if(X==K){
38                     while(pre[tail]){
39                         tail = pre[tail];//往上回查找
40                         ans ++ ;//答案加一
41                     }
42                     printf("%d\n",ans);
43                     return 0 ;
44                 }
45             }
46         }
47             
48     }
49     return 0 ;
50 }

 

bfs入门

标签:scan   模拟   open   fine   stream   return   mat   head   math   

原文地址:http://www.cnblogs.com/wahahaljy/p/6900727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!