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题目大意:一个农民找他的牛,告诉你 他和牛的位置(牛位置保持不动),他有三种走法 往前一步,往后一步和走到他当前位置一倍的位置(卧槽这就是个bug,怎么可能跑那么快)每次动一次需要一分钟,问你最短需要多少分钟找到他的牛简单的bfs
1 #include<iostream> 2 #include<queue> 3 #include<cstring> 4 using namespace std; 5 #define M 100010 6 #define X 100000 7 struct place 8 { 9 int x,step; 10 }; 11 bool vid[M];//记录是否走过 12 int main() 13 { 14 int bfs(place n,place k); 15 place n,k; 16 n.step=0; 17 while(cin>>n.x>>k.x) 18 cout<<bfs(n,k)<<endl; 19 return 0; 20 } 21 int bfs(place n,place k) 22 { 23 if(n.x==k.x)//先判断是否在相同的位置 24 return 0; 25 memset(vid,0,sizeof(vid)); 26 queue<place>q; 27 place x; 28 while(1) 29 { 30 x.step=n.step+1; 31 if(n.x<k.x)//剪枝,只有当当前位置小于牛的位置才往前走 32 { 33 x.x=n.x*2; 34 if(x.x<=X&&!vid[x.x]) 35 { 36 if(x.x==k.x)//bfs最好还是先判断不然会多花时间 37 return x.step; 38 q.push(x);vid[x.x]=true; 39 } 40 x.x=n.x+1; 41 if(!vid[x.x]) 42 { 43 if(x.x==k.x) 44 return x.step; 45 q.push(x);vid[x.x]=1; 46 } 47 } 48 x.x=n.x-1; 49 if(!vid[x.x]&&x.x>=0)//不要以为只有大于才往后走,可能出现你往后走一步之后全翻倍走得情况 50 { 51 if(x.x==k.x) 52 return x.step; 53 q.push(x); 54 vid[x.x]=1; 55 } 56 n=q.front(); 57 q.pop(); 58 } 59 } 60 /* 61 附上几组比较重要的数据 62 0 100000 63 22 64 100000 0 65 100000 66 7 3072 67 10 68 */