OpenJudge 2971 抓住那头牛

 

总时间限制: 
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

 

普通的BFS。要注意剪枝和开大数组。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cmath>
 5 using namespace std;
 6 int n,k;
 7 bool vis[300001];
 8 int pos[1000000];
 9 int step[1000000];
10 void BFS(){
11     int hd=0,tl=1;
12     pos[++hd]=n;
13     step[hd]=0;
14     while(hd<=tl){
15         int now=pos[hd];
16         if(now==k){
17             printf("%d\n",step[hd]);
18             return;
19         }
20         int next=now*2;
21         if(next>=0 && next<=100000 && !vis[next]){
22             vis[next]=1;
23             pos[++tl]=next;
24             step[tl]=step[hd]+1;}
25         next=now+1;
26         if(next<=100000 && !vis[next]){
27             pos[++tl]=next;
28             vis[next]=1;
29             step[tl]=step[hd]+1;}
30         next=now-1;
31         if(next>=0 && !vis[next] ){
32             vis[next]=1;
33             pos[++tl]=next;
34             step[tl]=step[hd]+1;}
35         hd++;
36     }
37 }
38 int main(){
39     scanf("%d%d",&n,&k);
40     BFS();
41     return 0;
42 }

 

posted @ 2016-08-12 21:35  SilverNebula  阅读(1974)  评论(0编辑  收藏  举报
AmazingCounters.com