Catch That Cow(广搜)
个人心得:其实有关搜素或者地图啥的都可以用广搜,但要注意标志物不然会变得很复杂,想这题,忘记了标志,结果内存超时;
将每个动作扔入队列,但要注意如何更简便,更节省时间,空间
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?
InputLine 1: Two space-separated integers: N and KOutputLine 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
Hint
The 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.
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<queue> 5 using namespace std; 6 int sum; 7 int ok=0; 8 struct Node 9 { 10 int x; 11 int y; 12 13 }; 14 int book[100005]; 15 16 void dfs(int n,int m) 17 { 18 memset(book,0,sizeof(book)); 19 queue<Node >s; 20 book[n]=1; 21 Node t; 22 t.x=n;t.y=0; 23 s.push(t); 24 int a; 25 Node tt; 26 while(!s.empty()) 27 { 28 a=s.front().x*2; 29 tt.x=a,tt.y=s.front().y+1; 30 if(a==m) 31 { 32 sum=tt.y; 33 return ; 34 35 } 36 if(tt.x>=0&&tt.x<=100000) 37 if(!book[a]) 38 { 39 book[a]=1; 40 s.push(tt); 41 42 } 43 a=s.front().x+1; 44 tt.x=a; 45 tt.y=s.front().y+1; 46 if(a==m) 47 { 48 sum=tt.y; 49 return ; 50 51 } 52 if(tt.x>=0&&tt.x<=100000) 53 if(!book[a]) 54 { 55 book[a]=1; 56 s.push(tt); 57 58 }; 59 a=s.front().x-1; 60 tt.x=a,tt.y=s.front().y+1; 61 if(a==m) 62 { 63 sum=tt.y; 64 return ; 65 66 } 67 if(tt.x>=0&&tt.x<=100000) 68 if(!book[a]) 69 { 70 book[a]=1; 71 s.push(tt); 72 73 } 74 s.pop(); 75 76 } 77 return ; 78 79 80 } 81 int main() 82 { 83 84 int n,m; 85 while(cin>>n>>m) 86 { 87 sum=0; 88 if(n>=m) sum=n-m; 89 else 90 dfs(n,m); 91 cout<<sum<<endl; 92 93 } 94 return 0; 95 96 }