Light OJ:1141 Number Transformation(BFS+素因子)

来源:互联网 发布:新东方在线网络课程 编辑:程序博客网 时间:2024/06/06 15:38
      1141 - Number Transformation
  PDF (English)StatisticsForum
Time Limit: 2 second(s)Memory Limit: 32 MB

In this problem, you are given an integer number s.You can transform any integer numberA to another integer number Bby adding x to A. This x is an integer number which is aprime factor ofA (please note that 1 and A are not beingconsidered as a factor ofA). Now, your task is to find the minimumnumber of transformations required to transforms to another integernumber t.

Input

Input starts with an integer T (≤ 500),denoting the number of test cases.

Each case contains two integers: s (1 ≤ s ≤100) and t (1 ≤ t ≤ 1000).

Output

For each case, print the case number and the minimum numberof transformations needed. If it's impossible, then print-1.

Sample Input

Output for Sample Input

2

6 12

6 13

Case 1: 2

Case 2: -1

 


题目大意:给你两个数s和t,s加上s的一个素因子得到新的s,问至少这样几步可以使得s变成t。
解题思路:素数打表,然后把1000以内所有的数的素因子放到vector里面,然后bfs搜索,一旦搜到符合s变成t,那么肯定是最少步数,且用vis记录到达过的状态,避免重复搜索(因为没加vis比赛时超内存了,因为比如你输入6 999,那么中间过程可能是
6+2=8
6+3=9
8+2=10
9+3=12
10+2=12
10+5=15
12+2=14
12+3=15,其中12,15此时被最少搜索两次,后面还有可能再次搜到它们,要达到999很难,所以把这些状态要标记,避免重复搜索)。
代码如下:
#include <cstdio>#include <cstring>#include <vector>#include <queue>using namespace std; int a,b,ans;int su[1010];int vis[1010];vector<int> v[1010];struct node{int num,step;};void dabiao(){su[0]=1;su[1]=1;for(int i=2;i<1010;i++){if(su[i]==1){continue;}for(int j=i*2;j<1010;j=j+i){su[j]=1;}}for(int i=0;i<1010;i++){v[i].clear();}for(int i=0;i<1010;i++){for(int j=2;j<i;j++){if(su[j]==0&&i%j==0){v[i].push_back(j);}}}}void bfs(){memset(vis,0,sizeof(vis));node x,y;x.num=a;x.step=0;queue<node> q;while(!q.empty()){q.pop();}q.push(x);vis[a]=1;while(!q.empty()){x=q.front();q.pop();if(x.num==b){ans=x.step;break;}for(int i=0;i<v[x.num].size();i++){y.num=x.num+v[x.num][i];if(y.num<=b&&vis[y.num]==0){vis[y.num]=1;y.step=x.step+1;q.push(y);}}}}int main(){dabiao();//素数打表+素因子打表 int t;scanf("%d",&t);int cnt=1;while(t--){scanf("%d%d",&a,&b);ans=-1;//初始化结果 bfs();printf("Case %d: %d\n",cnt++,ans);}return 0;} 


0 0
原创粉丝点击