1198: 数轴

1198: 数轴
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 3 Solved: 1
[Submit][Status][Web Board]
Description
John想抓到一头牛, John在一个数轴的一个位子X,牛在数轴的另一个位子Y。但John这个人在一个单位时间内可以有三种走的方式,一是走到数轴的下一格,或是前一格,或是他的数轴的两倍的格子上,求此人最快抓到牛的时间。

Input
输入X,Y,存在多组输入

Output
此人最快抓到牛的时间

Sample Input
5 17
Sample Output
4
HINT
搜索算法
my answer:

#include<iostream>
#include<queue>
using namespace std;
typedef struct dot{
    int x,step;
}dot;
 
int main()
{
    int x,y;
    while(cin>>x>>y)
    {
        dot g;
        int ok=0;
        g.x =x;
        g.step = 0;
        if(g.x == y)
        {
            cout<<0<<endl;
            continue;
        }
        queue<dot>q;
        q.push(g);
        while(!q.empty() )
        {
            dot t,next;
            t=q.front() ;q.pop() ;
            for(int i=0 ;i!=3;i++)
            {
                switch(i)
                {
                    case 0:next.x=t.x - 1;break;
                    case 1:next.x=t.x + 1;break;
                    case 2:next.x=t.x * 2;break;
                }
                next.step =t.step +1;
                if(next.x == y)
                {
                    ok=1;
                    cout<<next.step <<endl;
                    break;
                }
                else{
                     q.push(next); 
                }
            }
            if(ok)break;
        } 
    }
}
原文地址:https://www.cnblogs.com/NYNU-ACM/p/4236902.html