B15 BFS 抓住那头牛

视频链接:116 抓住那头牛 最小步数_哔哩哔哩_bilibili

Luogu P1588 [USACO07OPEN]Catch That Cow S

 

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

const int N=100005;
int x, y, dis[N];

void bfs(){
  memset(dis,-1,sizeof dis); dis[x]=0;
  queue<int> q; q.push(x);
  while(q.size()){
    int x=q.front(); q.pop();
    if(x+1<N && dis[x+1]==-1){
      dis[x+1]=dis[x]+1; //前进一步
      q.push(x+1);
    }
    if(x-1>0 && dis[x-1]==-1){
      dis[x-1]=dis[x]+1; //后退一步
      q.push(x-1);
    }
    if(2*x<N && dis[2*x]==-1){
      dis[2*x]=dis[x]+1; //走到2x位置
      q.push(2*x);
    }
    if(x==y){printf("%d\n",dis[y]);return;}
  }
}
int main(){
  int T; cin>>T;
  while(T--) cin>>x>>y, bfs();
}

 

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

const int N=100005;
int a, b, dis[N];
int q[N];

void bfs(){
  memset(dis, -1, sizeof dis);
  dis[a]=0;int h=0, t=0; q[0]=a;
  while(h<=t){
    int x=q[h++];
    if(x+1<N && dis[x+1]==-1){
      dis[x+1]=dis[x]+1; //前进一步
      q[++t]=x+1; 
    }
    if(x-1>0 && dis[x-1]==-1){
      dis[x-1]=dis[x]+1; //后退一步
      q[++t]=x-1; 
    }
    if(2*x<N && dis[2*x]==-1){
      dis[2*x]=dis[x]+1; //走到2x位置
      q[++t]=2*x;
    }
    if(x==b){printf("%d\n",dis[b]);return;}
  }
}
int main(){
  int T; cin>>T;
  while(T--)
    cin>>a>>b, bfs();
}

 

posted @ 2023-06-04 11:21  董晓  阅读(396)  评论(0编辑  收藏  举报