【POJ】3278 Catch That Cow

题目链接:http://poj.org/problem?id=3278

题意:有一头奶牛跑到了K的位置,农夫在N的位置,求最短抓到奶牛的时间。

农夫有两种移动方式。

1、步行:一分钟内从x->x+1 或者 x->x-1。

2、传送:一分钟内从x->2x。

题解:一个BFS例题。基础练手用的。queue里其实有三种状态。x-1,x+1,2x。然后去试探鸭。

代码:

 1 #include<iostream>
 2 #include<queue>
 3 #include<cstring>
 4 #define Max 100010 
 5 using namespace std;
 6 int N,K;
 7 queue<int> qu;
 8 
 9 int vis[Max];
10 int step[Max];
11 
12 int bfs(int n,int k){
13     memset(vis,0,sizeof(vis));
14     int x;
15     qu.push(n);
16     vis[n] = 1;
17     step[n] = 0;
18     int head,next;
19     while(!qu.empty()){
20         head = qu.front();    //取出队首元素 
21         if(x == k)    
22             break;    //满足条件就跳出 
23         qu.pop();
24         
25         //分方向 
26         for(int i = 0; i < 3 ;i++){
27             if(i == 0)
28                 next = head-1;
29             else if(i == 1)
30                 next = head+1;
31             else if(i == 2)
32                 next = head*2;
33             if(next > Max || next < 0 )
34                 continue;
35             if( !vis[next]){
36                 qu.push(next);
37                 vis[next] = 1;
38                 step[next] = step[head] + 1;
39             }
40             if(next == K)
41                 return step[next];    
42         }
43         
44     }
45     return -1;
46 
47 }
48 
49 int main(){
50     cin>>N>>K;
51     if(N >= K)
52         cout<< N-K<<endl;
53     else
54         cout<<bfs(N,K)<<endl;    
55     
56     return 0;
57 } 

猜你喜欢

转载自www.cnblogs.com/Asumi/p/9698302.html