P1588 Catch That Cow S

点击查看代码
#include<bits/stdc++.h>
using namespace std;

const int N=100005;
int dist[N];
int t;
int x,y;

int bfs(int start, int target)
{
    if(start>=target) return start-target;
    //1.初始化与启动
    memset(dist,-1,sizeof dist);
    queue<int> q;
    q.push(start);
    dist[start]=0;

    //2.开始循环
    while(!q.empty()){
        int u=q.front();
        q.pop();
        if(u==target) return dist[u];

        int moves[3]={u-1,u+1,2*u};
        for(int i=0;i<3;i++){
            int v=moves[i];
            if(v>=0&&v<=100000&&dist[v]==-1){
                dist[v]=dist[u]+1;
                q.push(v);
            }
        }
    }
    //3.结束
    return -1;
}

int main()
{
    cin>>t;
    while(t--){
        cin>>x>>y;
        cout<<bfs(x,y)<<endl;
    }

    return 0;
}
posted @ 2026-01-10 15:27  AnoSky  阅读(1)  评论(0)    收藏  举报