Catch That Cow (BFS luo搜 + 剪枝)
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
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.
结构体 + 数组标记,M E 。(心态爆炸 27次)2717 1/26 (魔改下去,一定有办法A掉
#include <iostream> #include <algorithm> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <map> #include <vector> #include <set> #include <queue> #include <stack> #include <cmath> #define mem(s,t) memset(s,t,sizeof(s)) #define ok return 0; #define TLE std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; int vis[100000+5]; int main() { TLE; int n,m,now,nx; while(cin>>n>>m) { if(n>=m) cout<<n-m<<endl; else { mem(vis,0); vis[n]=1; queue<int>q; while(!q.empty()) q.pop(); q.push(n); while(!q.empty()) { now = q.front(); q.pop(); if(now==m){ cout<<vis[now]-1<<endl; break;} nx = now + 1; if(nx<=100000 && !vis[nx]) q.push(nx),vis[nx]=vis[now]+1; nx = now - 1; if(nx<=100000 && !vis[nx] && nx>=0) q.push(nx),vis[nx]=vis[now]+1; nx = now*2; if(nx<=100000 && !vis[nx]) q.push(nx),vis[nx]=vis[now]+1; } } } ok; }