CodeForces - 520B
直接进行bfs就行,不过如果不加剪枝的话可能会TLE,,,
突然发现很长时间不写bfs都不会写了,,,
剪枝只需要在n>m是剪掉n*2,在n<=1时剪掉n-1即可。
#include<iostream>
#include<queue>
using namespace std;
struct h{
int k;
int s;
};
bool vis[100005];
int main(){
int ans=0;
int n,m;
cin>>n>>m;
queue<h>p;
if(n>=m){
cout<<n-m<<endl;
}
else{
p.push(h{n,0});
vis[n]=1;
while(!p.empty()){
h x=p.front();
p.pop();
if(x.k==m){
cout<<x.s<<endl;
break;
}
if(x.k>1&&!vis[x.k-1]){
p.push(h{x.k-1,x.s+1});
vis[x.k-1]=1;
}
if(x.k<m&&!vis[x.k*2]){
p.push(h{x.k*2,x.s+1});
vis[x.k*2]=1;
}
}
}
return 0;
}