4001:抓住那头牛(bfs)

 

总时间限制: 
2000ms
 
内存限制: 
65536kB
描述

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

1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
 
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
输入
两个整数,N和K
输出
一个整数,农夫抓到牛所要花费的最小分钟数
样例输入
5 17
样例输出
4

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN=100005;
 4 struct Node{
 5     int x;
 6     int step;
 7     Node(int xx,int ss):x(xx),step(ss){}
 8 };
 9 int visit[MAXN];
10 queue <Node> q;
11 int main() {
12     int a,cow;
13     cin>>a>>cow;
14     if(!q.empty())q.pop();
15     memset(visit,0,sizeof(visit));
16     visit[a]=1;
17     q.push(Node(a,0));
18     while(!q.empty()){
19         Node p=q.front();
20         q.pop();
21         if(p.x==cow){
22             cout<<p.step<<endl;
23             return 0;
24         }
25         if(!visit[p.x+1]&&p.x+1<MAXN){
26             visit[p.x+1]=1;
27             q.push(Node(p.x+1,p.step+1));
28         }
29         if(!visit[p.x-1]&&p.x-1>=0){
30             visit[p.x-1]=1;
31             q.push(Node(p.x-1,p.step+1));
32         }
33         if(!visit[p.x*2]&&p.x*2<MAXN){
34             visit[p.x*2]=1;
35             q.push(Node(p.x*2,p.step+1));
36         }
37         
38     }
39     
40     return 0;
41 }

猜你喜欢

转载自www.cnblogs.com/aiqinger/p/12625698.html
今日推荐