POJ 3278 抓牛简单广搜

来源:互联网 发布:产品标贴制作软件 编辑:程序博客网 时间:2024/04/30 14:47
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 75331 Accepted: 23781

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX+ 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 andK

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.

如Hint中所说,在一条线上抓,输入的N是人的起始位置,K是牛的人要到达的位置
#include <iostream>#include <queue>#include <cstdio>#include <cstring>using namespace std;const int maxn = 100050;int main(){    queue<int> a;    int vis[maxn];    int n,k;    cin>>n>>k;    memset(vis,0,sizeof(vis));    int flag = 0;    vis[n]=1;    int step = 0;    a.push(n);if(n!=k){  //要考虑这种情况,不然0步输出的是1步while(!a.empty()&&!flag){            int t = a.size();//队列中元素的个数            step++;    while(t--){ //参考比较模板的while(head<tail),这里直接用的STL,所以形式变了            int next,nnext[3];            next = a.front();            nnext[0]=next+1;            nnext[1]=next-1;            nnext[2]=next*2;            a.pop();            for(int i = 0;i<3;i++){                if(nnext[i]==k){                        flag=1;                        break;}                    if(nnext[i]>=1&&nnext[i]<=100000&&!vis[nnext[i]]){                        vis[nnext[i]]=1;                        a.push(nnext[i]);                    }                }                if(flag) break;//我觉得这一步能省时间的,可是去掉不去掉提交的时间都一样,可能数据比较小吧                                //当n=1,k=2时,在step=1时,进栈的顺序是2,0,0,找到第一个2直接退出,因为此时step都是1            }    }}cout<<step<<endl;return 0;}


0 0
原创粉丝点击