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
- BFS 3071. Number Game
- TOJ--3071:Number Game (BFS)
- Number Game
- Number Game
- Number Game
- Poj 1708 Game (BFS)
- HDU2216:Game III(BFS)
- HDU2216:Game III(BFS)
- Fire Game(BFS)
- Fire Game(BFS)
- FZU2150 Fire Game (bfs)
- [BFS]HDU1045 Fire Game
- UESTC 485 Game (BFS)
- 【poj1101】The Game BFS
- fzu2150 Fire Game bfs
- Fire Game (BFS)
- fzu Fire Game bfs
- FZU2150 Fire Game (BFS)
- Action、Category、Data、Extras知识详解
- 排序算法学习笔记
- hdu 1240 Asteroids!(BFS)
- Java 循环嵌套问题
- Candy
- BFS 3071. Number Game
- 【C++】处理CSDN博文源码
- CALayer用法
- 数据结构——顺序队列的C++实现
- GZIPOutputStream 数据压缩问题
- java中类与类关系,UML类图关系,设计模式
- HDOJ 题目1856More is better(并查集)
- C++ primer 第五版 中文版 9.2.7 节练习
- java基础巩固系列(五):ArrayList与HashSet的比较,以及HashCode分析