LightOJ-1141-Number Transformation

点击打开链接

LightOJ1141 :Number Transformation

时间限制:2000MS    内存限制:32768KByte   64位IO格式:%lld & %llu
描述

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

输入

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).

输出

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

样例输入

2

6 12

6 13

样例输出

Case 1: 2

Case 2: -1


题意:给两个数s, t,用s加上它的素因子(不包括1和它自身)得到另外一个数,然后重复之前的操作,加上当前数的素因子。。。直到得到t为止,问最少经过多少次的得到t


#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;	 
const int MAX = 1e3 + 10;
int vis[MAX],p[MAX];
int flag;
int s,t,ans;
const int ANS=0x3f3f3f3f/2;	//ANS没有具体的值,只要能大于最大的步数就行;目地是在下面bfs中记录最小的步数 
vector <int > v[MAX];	//vector不定长数组,在STL中用过,v[i]是二维数组,存放i的质因数,如v[6]存的是2 3 
struct node{
	int x;
	int step;
};
void dabiao()	//找出1~MAX所有数的质因数,存到vector数组中 
{
	int i,j;
	p[1]=1;
	for(i=2;i<MAX;i++)
		if(!p[i])
		{
			for(j=i+i;j<MAX;j+=i)
				p[j]=1;
		}
	for(i=2;i<MAX;i++)
		for(j=2;j<MAX;j++)
			if(i%j==0&&!p[j])
				v[i].push_back(j);
}
void bfs()
{
	int i,j;
	node w;
	queue <node> qu;
	memset(vis,0,sizeof(vis));
	vis[s]=1;
	w.x=s;
	w.step=0;
	qu.push(w);
	while(!qu.empty())
	{
		w=qu.front();
		qu.pop();
		if(w.x==t)
		{
			flag=1;
			ans=min(ans,w.step);
			continue;
		}
			for(i=0;i<v[w.x].size();i++)
			{
				node q;
				q.x=w.x+v[w.x][i];
				q.step=w.step+1;
				if(q.x<=t&&!vis[q.x])
				{
					vis[q.x]=1;
					qu.push(q);
				}
			}
	}	
}
int main()
{
	int T,k=1;
	dabiao();
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&s,&t);
		if(s==t)
		printf("Case %d: 0\n",k++);
		else if(!p[s]||!p[t])
		printf("Case %d: -1\n",k++);
		else{
			flag=0;
			ans=ANS;	//如果省去这一步,在第二组数据中,ans会等于上组数据得到的ans的值,会很小,在bfs中比较会出错 
			bfs();
			if(flag)
			printf("Case %d: %d\n",k++,ans);
			else
			printf("Case %d: -1\n",k++);
		}		
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值