LightOJ 1141 Number Transformation 【BFS+分解质因子+优先队列】

题意: 给你一个整数A和B,A可以加上自己本身的质因数(不包括1和本身)【这点很重要】,从而等于B,问A通过加的操作的最少次数。我是用优先队列实现的,代码如下:

/* 题目要去一个数能否通过加除了自身和零的质因数==另一个数*/ 
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
int a,b,out,res;
int vis[1020],num[1020];
struct node{
	int x;
	int temp;
	bool friend operator < (node a,node b){
		return a.temp>b.temp;
	}
};
void fenjie(int n){
	res=0;
	int m=n;
	for(int i=2;i*i<=n;i++)
	{
		if(n%i==0)
		 {
		 	num[res++]=i;
		 	while(n%i==0)
		 	  n/=i;
		 }
	}
	if(n!=1&&n!=m) //这题的坑在n!=m这一片,一定不能忘记! 
	  num[res++]=n;   
}
void BFS(){
	memset(vis,0,sizeof(vis));
	priority_queue<node>que;
	node e1,e2;
	e1.x=a,e1.temp=0;
	vis[e1.x]=1;
	que.push(e1);
	int ans=-1;
	while(!que.empty())
	{   
	    memset(num,0,sizeof(num));
		e2=que.top();
		que.pop();
		if(e2.x==b)
		{
			ans=e2.temp;
			break;
		}
		fenjie(e2.x);
		for(int i=0;i<res;i++)
		{
			e1.x=e2.x+num[i];
			e1.temp=e2.temp+1;
			if(e1.x<=b && !vis[e1.x])
			{
				vis[e1.x]=1;
				que.push(e1);
			}
		}
	}
	if(ans==-1)
	   cout<<-1<<endl;
	else
	   cout<<ans<<endl;
}
void solve()
{
	int n;
	cin>>n;
	out=1;
	while(n--){
	cin>>a>>b;
	cout<<"Case "<<out++<<": ";
	if(a>b)
	{
		cout<<-1<<endl;;
		continue;
	}
	if(a==b)
	{
		cout<<0<<endl;
		continue;
	}
	BFS();
    }
} 
int main()
{   
    solve();
	return 0;
}

ps:想带你去洛阳!

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 x is 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

扫描二维码关注公众号,回复: 2561806 查看本文章

6 13

Sample Output

Case 1: 2

Case 2: -1

猜你喜欢

转载自blog.csdn.net/LOOKQAQ/article/details/81348792
今日推荐