LightOJ1141 :Number Transformation
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;
}