题意:给你n和k,问你n最少花费多少代价能得到k;
有两种变换:1、n++或者n--;
2、n=n*2;
两种代价每次的花费都是1;
思路:一维的bfs,每次入队三个点,一个是n+1,一个是n-1,一个是n*2的点;
#include<iostream> #include<algorithm> #include<cstring> #include<queue> #define maxn 100020 using namespace std; int step[maxn*2]; int visit[maxn*2]; int main() { queue<int>q; int n,k; while(cin>>n>>k) { if(n>k) cout<<n-k<<endl; else if(n==k) { cout<<"0 "; } else { memset(visit,0,sizeof(visit)); memset(step,0,sizeof(step)); visit[n]=1;step[n]=0;int flag=0; while(!q.empty()) { q.pop(); } q.push(n); while(!q.empty()) { int temp=q.front(); q.pop(); int now;//cout<<"z "; for(int i=1;i<=3;i++) { if(i==1) now=temp+1; else if(i==2) now=temp-1; else now=temp*2; if(visit[now]==0&&now<=maxn&&now>=0) { q.push(now); step[now]=step[temp]+1; visit[now]=1; } if(now==k) { cout<<step[now]<<endl;flag=1; break; } } if(flag==1) break; } } } return 0; }