LightOJ - 1141 Number Transformation ——————BFS+素因子分解

冷不防 2022-05-12 03:14 262阅读 0赞

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


要注意A是不断变化的,所以它的质因子也会变化
还有啊注意A的质因子不能有1,A


  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int s,t,ans;
  4. int cnt;
  5. int num,T;
  6. int p[1000];
  7. bool vis[3000];
  8. struct node {
  9. int x,step;
  10. node(){
  11. };
  12. node(int _x,int _step)
  13. {
  14. x=_x; step=_step;
  15. }
  16. bool operator < (const node &b)const
  17. {
  18. return step>b.step;
  19. }
  20. };
  21. void init(int n)
  22. {
  23. memset(p,0,sizeof(p));
  24. cnt=0;
  25. int z=n;
  26. for(int i=2;i*i<=n;i++)
  27. {
  28. if(n%i==0)
  29. {
  30. p[cnt++]=i;
  31. while(n%i==0) n/=i;
  32. }
  33. }
  34. if(n!=1&&n!=z) p[cnt++]=n;
  35. }
  36. void bfs(int s,int t)
  37. {
  38. memset(vis,0,sizeof(vis));
  39. priority_queue<node> que;
  40. node e1,e2;
  41. que.push(node(s,0));
  42. vis[s]=1;
  43. while(que.size())
  44. {
  45. e1=que.top();que.pop();
  46. if(e1.x==t)
  47. {
  48. ans=e1.step;
  49. break;
  50. }
  51. init(e1.x);
  52. for(int i=0;i<cnt;i++)
  53. {
  54. e2.x = e1.x + p[i];
  55. e2.step = e1.step + 1;
  56. if(!vis[e2.x] && e2.x <= t)
  57. {
  58. vis[e2.x]=1;
  59. if(e2.x==t)
  60. {
  61. ans=e2.step;
  62. break;
  63. }
  64. que.push(e2);
  65. }
  66. }
  67. }
  68. }
  69. int main()
  70. {
  71. scanf("%d",&num);
  72. T=num;
  73. while(num--)
  74. {
  75. scanf("%d %d",&s,&t);
  76. ans=-1;
  77. bfs(s,t);
  78. printf("Case %d: %d\n",T-num,ans);
  79. }
  80. return 0;
  81. }

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读

    相关 因子分解

    概念:所谓质因子分解是将一个正整数n写成一个或多个质数的乘积形式。 例如:6=2\3,180=2\2\3\3\5,也可以写成指数形式,例如 180=2^2\3^2\5^1;