BFS 3071. Number Game

来源:互联网 发布:java发送socket请求 编辑:程序博客网 时间:2024/06/05 05:49
There is an interesting game. We start with a number K. Then three operations is allowed:

1. Multiply current number by 2
2. Divide current number by 2, if current number is even.
3. Increase current number by 1

Our target is to get number P with minimum operations. You can assume 0 <P,K < 100000, and the number can not be greater than or equal to 100000 at any time.

Input

The first line is an integer T, the number of test cases. Then T cases follows.

Each test case contain two numbers K and P in one line separated by a space.

Output

Output the minimum number of operations. If it is impossible to get P fromK, output -1 instead.

Sample Input

211 2099999 50000

Sample Output

7

-1

#include<iostream>using namespace std;const int n=100000;int visit[n];struct num{int x,step;}c[n];int bfs(int s,int t){memset(visit,0,sizeof(visit));visit[s]=1;c[0].x=s;c[0].step=0;int top=1,temp;for(int i=0;i<top;i++){if(c[i].x==t)return c[i].step;temp=c[i].x*2;if(temp<n&&!visit[temp]){visit[temp]=1;c[top].step=c[i].step+1;c[top].x=temp;top++;}if(c[i].x%2==0){temp=c[i].x/2;if(temp>0&&!visit[temp]){visit[temp]=1;c[top].step=c[i].step+1;c[top].x=temp;top++;}}temp=c[i].x+1;if(temp<n&&!visit[temp]){visit[temp]=1;c[top].step=c[i].step+1;c[top].x=temp;top++;}}return -1;}int main(){int N,s,t;cin>>N;while(N--){cin>>s>>t;cout<<bfs(s,t)<<endl;}return 0;}


0 0
原创粉丝点击