您的位置:首页 > 其它

【BFS】HDU2717Catch That Cow

2016-04-21 20:41 302 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

Problem 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

HintThe 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.

好吧,数据访问越界两次,这里需要注意一点就是不能让*2一直乘下去,大于2*k就没有必要乘下去了。

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
int vis[2000010];
struct node
{
int x,t;
bool friend operator <(node a,node b)
{
return a.t>b.t;
}
};
int bfs(int s,int e)
{
priority_queue<node>q;
memset(vis,0,sizeof(vis));
node st;
st.x=s;
st.t=0;
vis[st.x]=1;
q.push(st);
while(!q.empty()){
st=q.top();
q.pop();
if(st.x==e)
return st.t;
node next;
next.x=st.x+1;
next.t=st.t+1;
if(vis[next.x]==0){
vis[next.x]=1;
q.push(next);
}
next.x=st.x-1;
next.t=st.t+1;
if(vis[next.x]==0){
vis[next.x]=1;
q.push(next);
}
next.x=st.x*2;
next.t=st.t+1;
if(next.x<=3*e&&vis[next.x]==0){
vis[next.x]=1;
q.push(next);
}
}
}
int main()
{
int n,m;
cin.sync_with_stdio(false);
while(cin>>n>>m)
{
cout<<bfs(n,m)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: