Problem 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?
* 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
4HintThe fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
简单广搜,坑爹的注意起点等于终点就行了;
#include<map> #include<set> #include<cmath> #include<queue> #include<bitset> #include<math.h> #include<vector> #include<string> #include<stdio.h> #include<cstring> #include<iostream> #include<algorithm> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; struct node{ int x,step; }s,e,q,p; int dir[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}}; int next1[2]={1,-1}; int vis[1000005]; bool judge(node a){ if(a.x<0||a.x>1000000||vis[a.x]) return false; return true; } int bfs(){ queue<node>que; s.step=0; vis[s.x]=1; que.push(s);int s=1; while(!que.empty()){ q=que.front();//printf("%d->%d\n",q.x,q.step); que.pop(); for(int i=0;i<2;i++){ p=q; p.x=q.x+next1[i]; if(judge(p)){ vis[p.x]=1; p.step++; que.push(p);//printf("%d %d %d %d\n",p.x,p.y,e.x,e.y); if(p.x==e.x) return p.step; } } p=q; p.x=q.x*2;//printf("%d~~\n",p.x); if(judge(p)){ vis[p.x]=1; p.step++; que.push(p); if(p.x==e.x) return p.step; } } } int main(){ int a,b; while(~scanf("%d%d",&a,&b)){ memset(vis,0,sizeof(vis)); s.x=a,e.x=b; if(s.x==e.x)printf("0\n"); else printf("%d\n",bfs()); } return 0; }