Description
In this problem, you are given an integer number s. You can transform any integer number A to another integer number B by adding x to A. This xis an integer number which is a prime factor of A (please note that 1 and A are not being considered as a factor of A). Now, your task is to find the minimum number of transformations required to transform s to another integer number 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 number of transformations needed. If it's impossible, then print -1.
Sample Input
2
6 12
6 13
Sample Output
Case 1: 2
Case 2: -1
题意:
例如:6+3=9,9+3=12加了两次
6+3=9,9+3=12,12的质因数只有2,3所以这种方案不行
6+2=8,8+2=10,10的质因数只有2,5所以不行
所以例二输出-1
利用搜索的方法,每次都枚举当前数的所有质因数,而且这里不需要标记,直到当前记录值等于目标值,这时也不要返回,用一个开始赋值很大的数来不断地更新最小值。
这么一来的话,就真的是每种情况都得枚举到了,这是会超时的!虽然我特意舍弃DFS而用了BFS还是不能幸免~~~~~
所以要进行优化,用一个开始赋值非常大的数组,然后每次记录当前入队列的节点他的当前值是什么,记下他的当前走了几步,后面每次当一个节点进队列时,就可以判断一下
他当前的步数是否小于以前走过的,如果小于就入队列,不小于就不进,这样就减少了很多毫无意义的尝试了
最后不得不说一句,做质因数标记那个数组在程序输入之前自动做好就行了,也花不了多少时间,而我竟然多次一举,去写了个辅助程序........................
#include"iostream" #include"algorithm" #include"cstring" #include"cstdio" #include"queue" using namespace std; int book[1010]; int mark[1010]; struct node { int as; int step; }; const int maxn=1000000000; int ans=1000000000; int flag; int c; int a; int b; int step=0; void BFS() { memset(mark,0x3f,sizeof(mark)); queue<struct node> que; struct node cc,e,t; cc.as=a; cc.step=0; que.push(cc); while(!que.empty()) { e=que.front(); que.pop(); if(e.as==b) { if(ans>e.step) ans=e.step; } for(int i=2;i<e.as;i++) { if(e.as%i) continue; if(book[i]!=1) continue; //cout<<"iqian"<<i<<endl; // cout<<i<<endl; if(mark[e.as+i]>e.step+1) { t=e; t.as+=i; if(t.as>b) continue; t.step++; mark[t.as]=t.step; que.push(t); } } } } int main() { int n,f; book[1]=1; book[2]=1; book[3]=1; book[5]=1; book[7]=1; book[11]=1; book[13]=1; book[17]=1; book[19]=1; book[23]=1; book[29]=1; book[31]=1; book[