LightOJ 1141 Program E

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

  1. #include <iostream>  
  2. #include <cstdio>  
  3. #include <cstring>  
  4. #include <algorithm>  
  5. #include <queue>  
  6. #include <cmath>  
  7. using namespace std;  
  8.   
  9. #define MAX 0x3f3f3f3f  
  10.   
  11. typedef struct{  
  12.     int step;  
  13.     int now;  
  14. }Node;  
  15.   
  16. int s, t;  
  17. bool prime[1010];  
  18. int marks[1001];  
  19.   
  20. int BFS(){  
  21.     queue<Node> q;  
  22.     Node start;  
  23.     start.now = s;  
  24.     start.step = 0;  
  25.     q.push( start );  
  26.   
  27.     memset( marks, 0x3f, sizeof( marks ) );  
  28.   
  29.     int ans = MAX;  
  30.   
  31.     while( !q.empty() ){  
  32.         Node n = q.front();  
  33.         q.pop();  
  34.   
  35.         if( n.now == t ){  
  36.             ans = min( ans, n.step );  
  37.             continue;  
  38.         }  
  39.   
  40.         for( int i = 2; i < n.now; i++ ){  
  41.             if( n.now % i != 0 || !prime[i] ){  
  42.                 continue;  
  43.             }  
  44.             if( n.now + i > t ){  
  45.                 continue;  
  46.             }  
  47.             if( marks[n.now+i] > n.step + 1 ){  
  48.                 Node temp;  
  49.                 temp.now = n.now + i;  
  50.                 temp.step = n.step + 1;  
  51.                 marks[n.now+i] = temp.step;  
  52.                 q.push( temp );  
  53.             }  
  54.         }  
  55.     }  
  56.   
  57.     if( ans < MAX ){  
  58.         return ans;  
  59.     }  
  60.   
  61.     return -1;  
  62. }  
  63.   
  64. int main(){  
  65.     int T, Case = 1;  
  66.   
  67.     memset( prime, true, sizeof( prime ) );  
  68.   
  69.     for( int i = 2; i <= 1000; i++ ){  
  70.         for( int j = 2; i * j <= 1000; j++ ){  
  71.             prime[i*j] = false;  
  72.         }  
  73.     }  
  74.   
  75.     cin >> T;  
  76.     while( T-- ){  
  77.         cin >> s >> t;  
  78.         cout << "Case " << Case++ << ": " << BFS() << endl;  
  79.     }  
  80.     return 0;  
  81. }  
原文地址:https://www.cnblogs.com/xl1164191281/p/4678581.html