Bfs算法1.3(一维模板)

给定起点n,m,人可以左移-1、1或向前移动与2倍当前距离,求到m最短时间;

#include<iostream>
#include<queue>
#define INF 1000000;
using namespace std;
const int maxn=1010;
int dx[]= {-1,1,0,0};
int n,m;
struct Node
{
    int r,time;
    Node(int a,int b):r(a),time(b){}
    Node(){}
};
int visit[100001];
void bfs(Node x)
{
    queue<Node>Q;
    Node xx,x3;
    Q.push(x);
    while(!Q.empty())
    {
        xx=Q.front();
        Q.pop();
        for(int i=0; i<3; i++)
        {
            if(i!=2)
            {
                x3.r=xx.r+dx[i];
            }
            else
            {
                x3.r=xx.r*2;
            }
            if(x3.r>=0&&x3.r<=100000&&!visit[x3.r])
            {
                visit[x3.r]=1;
                x3.time=xx.time+1;
                if(x3.r==m)
                {
                    cout<<x3.time;
                    return ;
                }
                else
                {
                    Q.push(x3);
                }
            }
        }

    }
}
int main()
{
    cin>>n>>m;
    visit[n]=1;
    if(n==m){cout<<0;return 0;}
    if(n>=m){cout<<n-m;return 0;}
    bfs(Node(n,0));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/83065364