# 洛谷P1588 丢失的牛

## 二、代码及注释

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
#include<queue>
#define ll long long
using namespace std;
const int maxn=100005;
queue<int> q;
int x,y;
int vis[maxn];
int dis[maxn];
int main(){

freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);

int t;
cin>>t;
while(t--){
cin>>x>>y;
while(!q.empty()) q.pop();          //将队列清空
q.push(x);                          //读入起点
vis[x]=1;
while(!q.empty()){
int top=q.front();
q.pop();
int p;
p=top+1;                          //注意要用p来拓展，而不能修改top
if(p==y){
cout<<dis[top]+1<<endl;         //一定要用一个dis数组来存FJ的步数，注意bfs拓展次数不等于FJ的步数
break;
}
else if(p<=100000 && p>=0 && !vis[p]){
q.push(p);
vis[p]=1;
dis[p]=dis[top]+1;
}
p=top-1;
if(p==y){
cout<<dis[top]+1<<endl;
break;
}
else if(p<=100000 && p>=0 && !vis[p]){
q.push(p);
vis[p]=1;
dis[p]=dis[top]+1;
}
p=top*2;
if(p==y){
cout<<dis[top]+1<<endl;
break;
}
else if(p<=100000 && p>=0 && !vis[p]){
q.push(p);
vis[p]=1;
dis[p]=dis[top]+1;
}
}
}

return 0;
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客