POJ-4001(3入口のBFS)
4001:Catch That Cow
- 时间限制:
- 2000ms
- 内存限制:
- 65536kB
- 描述
-
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?
- 输入
- Line 1: Two space-separated integers: N and K
- 输出
- Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
- 样例输入
-
5 17
- 样例输出
-
4
- 提示
- 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.
Tips:
大致题意:
给定两个整数n和k
通过 n+1或n-1 或n*2 这3种操作,使得n==k
输出最少的操作次数
#include"iostream"
#include"queue"
#include"cstring"
using namespace std;
bool vis[3*100000];
class pos{
public:
int step;
int x;
};
int main(){
queue<pos> q;
int n,k;
while(cin>>n>>k){
memset(vis,false,sizeof(vis));
pos t1,t2;
t1.step=0;
t1.x=n;
q.push(t1);
vis[t1.x]=true;
while(!q.empty()){
t1=q.front();
q.pop();
if(t1.x==k){
cout<<t1.step<<endl;
break;}
if(t1.x-1>=0&&!vis[t1.x-1//t1.x-1>=0是剪枝操作,位置可以为0
t2.x=t1.x-1;
t2.step=t1.step+1;
q.push(t2);
vis[t1.x-1]=true;
}
if(t1.x+1<=2*k&&!vis[t1.x+1]){//t1.x+1<=2*k是剪枝操作,范围放大到2*k
t2.x=t1.x+1;
t2.step=t1.step+1;
q.push(t2);
vis[t1.x+1]=true;
}
if(2*t1.x<=2*k&&!vis[2*t1.x]){//2*t1.x<=2*k是剪枝操作,范围放大到2*k
t2.x=2*t1.x;
t2.step=t1.step+1;
q.push(t2);
vis[2*t1.x]=true;
}
}
}
}