OpenJudge

bfs

  • sully
    sully 17.8.31 回复

    #include<iostream>
    using namespace std;
    int v[100001],q[100005],n,k;
    int main()
    {
    int head=1,tail=1,minu=0,judge=0;
    cin>>n>>k;
    q[1]=n;
    while(head<=tail){
    int hh=head,tt=tail;
    for(int i=hh;i<=tt;i++){
    if(q[i]==k) {judge=1;break;};
    if(q[i]-1>=0&&!v[q[i]-1]){++tail;q[tail]=q[i]-1;v[q[i]-1]=1;}
    if(q[i]+1<=100000&&!v[q[i]+1]){++tail;q[tail]=q[i]+1;v[q[i]+1]=1;}
    if(q[i]*2<=100000&&!v[q[i]*2]){++tail;q[tail]=q[i]*2;v[q[i]*2]=1;}
    }
    if(judge) break;
    head=tt+1;
    minu++;
    }
    cout<<minu;
    }

想要评论吗?

注册OpenJudge账号,如果您已经注册,请先登入