Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 102339 | Accepted: 31988 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 long long n,k,x;//n起点,k终点,x中间变量 5 long long bo[100010],len[100010],que[100010];//bo标记点,一个点只能访问一次,len距离,que存队列 6 long long front,sear,i;//front队列读取位置,队列填入的位置 7 long long bfs() 8 { 9 if(n==k)return 0;//起点与终点相同 10 memset(bo,0,sizeof(bo)); //将所有点都标记为未访问 11 front=0;sear=0;//读取了0个点 填入完了1个 12 que[0]=n;len[0]=0;bo[n]=1;//填入一个点,长度为0,访问过起点 13 while(front<=sear)//访问的点超过写入点就结束 14 { 15 for(i=0;i<3;i++)//三个方向 16 { 17 if(i==0) x=que[front]-1; 18 else if(i==1) x=que[front]+1; 19 else if(i==2) x=2*que[front]; 20 if(x>=0&&x<=100000&&bo[x]==0) 21 { 22 bo[x]=1;//标记访问 23 len[++sear]=len[front]+1;//为上个点长度加一 24 que[sear]=x;//写入队列 25 if(x==k)return len[sear];//找到了点 26 } 27 } 28 front++;//访问下一个队列中的点 29 } 30 return -1; 31 } 32 int main() 33 { 34 while(scanf("%lld %lld",&n,&k)==2) 35 printf("%lld\n",bfs()); 36 return 0; 37 }