Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 116403 | Accepted: 36372 |
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
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.
Source
题目大意:农夫约翰被告知了一头逃亡牛的位置,并想立即赶上她。他开始于一个点N(0≤ N ≤100,000)和牛是在点K(0≤ K≤100,000),农民约翰有两种运输方式:步行和传送。
*散步:FJ可以从任何点移动X到点X - 1或X在单个分钟+ 1
*隐形传态:FJ可以从任何点移动X到点2× X在一分钟。
如果母牛不知道它的追求,根本不动,那么农夫约翰需要多长时间才能找回它?
解题思路:借助队列,进行广度搜索,最先跳出的是最短时间。
#include <iostream>
#include<stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int ans[100005];
int vis[100005];
int N,K;
queue<int>q;
int bfs(int pos,int end){//运用队列进行bfs搜索
q.push(pos);
ans[pos]=0;//步数初始化,第0步
vis[pos]=1;//对第一个数据标记
int x=0;
while (!q.empty()) {//对队列判断,是否循环
int t=q.front();//记录第一个数据
q.pop();//清空队列
for (int i=0; i<3; i++) {//列举每一种情况
if (i==0) x=t-1;
if (i==1) x=t+1;
if(i==2) x=2*t;
if (x>2*end||x<0||x>=100001) continue;//限制x的范围
if (!vis[x]){//对每一种情况判断,是否走过,防止死循环
vis[x]=1;//对走过的进行标记
q.push(x);//进入下一步
ans[x]=ans[t]+1;//记录时间
if (x==end) return ans[x];//判断条件,是否跳出;
}
}
}
return ans[x];
}
int main() {
while(scanf("%d%d",&N,&K)!=EOF) {
memset(vis, 0, sizeof(vis));//初始化数组
memset(ans, 0, sizeof(ans));//初始化数组
while (!q.empty()) q.pop();//清空队列
if (N>=K){
printf("%d",N-K);//如果n大于k只能减
}else printf("%d",bfs(N, K));//另一种情况
}
return 0;
}