LightOJ 1141 Number Transformation

Number Transformation

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

6 13

Sample Output

Case 1: 2

Case 2: -1

題意 每次s加上質因數,然後再求加過後結果的質因數,再加上去,到最後是否可以等於t;
題解 bfs ,一開始老是想dfs,並且題意還理解的有偏差。以下是代碼。

#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
const int MAX=1000000;
int pri[MAX],dis[MAX];
int kk=0;
void pirme()//打表求素數 
{
    memset(pri,0,sizeof(pri));
    pri[0]=pri[1]=1;
    for(int i=2;i<MAX;i++)
    {
        if(pri[i]==0)
        {
            for(int j=2;j*i<MAX;j++)
            pri[i*j]=1;
        }
    }
}

 void bfs(int a,int b)
 {
    memset(dis,0x3f,sizeof(dis));//將數組都存爲0x3f3f3f3f 
    queue<int>qu;
    qu.push(a) ;
    dis[a]=0;//起始位置爲0; 
    while(!qu.empty() )
    {
        int x=qu.front() ;
        qu.pop() ;
        if(x==b) return ;
        for(int i=2;i<x;i++)//求質因子; 
        {
            if(x%i==0&&pri[i]==0)
            {
                if(x+i>b) break;
                if(dis[x+i]>dis[x]+1)//更改步數 
                {
                    dis[x+i]=dis[x]+1;
                    qu.push(x+i); 
                 }
             }
         }
     }
 }


int main()
{
    int T;
    scanf("%d",&T);
    pirme();
    int Case=1;
    while(T--)
    {
        int s,t;
        scanf("%d%d",&s,&t);
        bfs(s,t);
        if(dis[t]!=0x3f3f3f3f) printf("Case %d: %d\n",Case++,dis[t]);
        else printf("Case %d: -1\n",Case++);

    }
    return 0;
}

代碼水平還是差啊,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章