#include<algorithm>
#include<queue>
#include<string.h>
#include<stack>
using namespace std;
struct node{
int x;
int step;
node(){
}
node(int _x,int _s):x(_x),step(_s){
}
};
int vit[20010];
int main(){
int n,m;
scanf("%d%d",&n,&m);
if(n>=m){
printf("%d\n",n-m);
}
else{
queue<node> q;
memset(vit,0,sizeof(vit));
node tmp;
q.push(node(n,0));
while(!q.empty()){
tmp = q.front();
q.pop();
if(tmp.x == m){
printf("%d\n",tmp.step);
break;
}
if(tmp.x-1>0 && !vit[tmp.x-1]){
q.push(node(tmp.x-1,tmp.step+1));
vit[tmp.x-1] = 1;
}
if(tmp.x*2 <=10000 &&!vit[tmp.x*2]){
q.push(node(tmp.x*2,tmp.step+1));
vit[tmp.x*2] = 1;
}
//printf("tip\n");
}
}
}
打分
题目已经写过很多次了,但是还是写错.记下来引以为戒.
题目大意,给定两个数a,b,通过两种操作将a变成b
一种是将a乘以2,一种是将a减1
这里可以用贪心的思路做,强行bfs搜也是可以,但是数据一大就容易T
首先如果a>b那么必然是直接减,因为变小的操作只有减
如果a<b那么有两种情况.如果b是奇数,那么必然最后一步是减操作,我们可以确定,因此可以先加回去b变成b+1
如果是偶数,那么必然最后一步是乘以2也可以还原,把b变成b/2
直到操作到b<=a的时候结束,结尾加上abs(a-b)就是全部的步骤数量,
思考的方式其实是倒着做,并不是用a去靠近b.而是用b去凑回a
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
int a,b,ans;
int main()
{
std::ios::sync_with_stdio(false);
//freopen("1.txt","r",stdin);
cin>>a>>b;
if(a>b)
ans=a-b;
else {
while(a<b){
if(b%2){
ans++;
b++;
}
else {
ans++;
b/=2;
}
}
ans+=abs(a-b);
}
cout<<ans<<endl;
return 0;
}