bfs搜索 搜索时注意先判断符合条件再入队列,不然会爆。
Catch That Cow
ac代码:
#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f,MAXN=100000000;
int vis[100000+5],cnt,row[15],m,n,ans=INF;
queue<pair<int,int> > que;
int main(){
scanf("%d%d",&n,&m);
if (n>=m){
printf("%d\n",n-m);
return 0;
}
que.push(make_pair(n,0));
while (!que.empty()){
pair<int,int> u=que.front(); que.pop();
int t=u.first,d=u.second;
if (t==m){
ans=d;
break;
}
if (t-1>=0&&t-1<=100000&&!vis[t-1]) {
que.push(make_pair(t-1,d+1));
vis[t-1]=1;
}
if (t+1>=0&&t+1<=100000&&!vis[t+1]){
que.push(make_pair(t+1,d+1));
vis[t+1]=1;
}
if (2*t>=0&&2*t<=100000&&!vis[2*t]){
que.push(make_pair(t*2,d+1));
vis[2*t]=1;
}
}
printf("%d\n",ans);
}