1100. 抓住那头牛

在这里插入图片描述
思路:
由于权值都为1,找最少时间,相当于找最短距离,用BFS来做
在这里插入图片描述

代码:

# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

const int N = 2e5 + 10;
int q[N],dis[N];
int n,k;

int bfs()
{
    
    
    int tt = 0,hh = 0;
    q[0] = n;
    memset(dis,-1,sizeof dis);
    dis[n] = 0;
    while(hh <= tt)
    {
    
    
        int t = q[hh++];
        if(t == k) return dis[t];
        if(t + 1< N && dis[t + 1] == -1)
        {
    
    
            dis[t + 1] = dis[t] + 1;
            q[++tt] = t + 1;
        }
        if(t - 1 >= 0 && dis[t - 1] == -1)
        {
    
    
            dis[t - 1] = dis[t] + 1;
            q[++tt] = t - 1;
        }
        if(t * 2 < N  && dis[t * 2] == -1)
        {
    
    
            dis[t * 2] = dis[t] + 1;
            q[++tt] = t * 2;
        }
    }
    return -1;
}

int main()
{
    
    
    cin >> n >> k;
    cout << bfs() << endl;
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45812180/article/details/115267932