Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 74836 | Accepted: 23623 |
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
农民要追上一头牛,给定两人位置,问最少要多久追上,抽象成一个坐标轴,农民只能坐标+1,-1或*2,简单BFS,还是模板
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 100010
int ans, n, k;
bool vis[maxn];
struct node{
int x, step;
}t, r;
bool judge(node v){
if(v.x < 0 || v.x > maxn || vis[v.x]){
return false;
}
return true;
}
queue<node > q;
void bfs(){
t.x = n;
t.step = 0;
q.push(t);
vis[t.x] = true;
while(!q.empty()){
t = q.front();
q.pop();
for(int i = 0; i < 3; i++){
if(i == 0){
r.x = t.x+1;
}
if(i == 1){
r.x = t.x-1;
}
if(i == 2){
r.x = t.x*2;
}
if(judge(r)){
r.step = t.step+1;
if(r.x == k){
printf("%d\n", r.step);
return ;
}
vis[r.x] = true;
q.push(r);
}
}
}
}
int main(){
memset(vis, false, sizeof(vis));
scanf("%d%d", &n, &k);
if(n >= k){
printf("%d\n", n-k);
}
else{
bfs();
}
return 0;
}