标签:
One can transform xinto x+d if dis divisor of x. Find out the minimum number of steps to transform a into b.
Two integers a and b.
(1≤a,b≤105)
The only integer denotes the minimum number of steps. Print −1if impossible.
1 6
3
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<queue> 5 #include<stack> 6 #include<cmath> 7 #define ll long long 8 #define pi acos(-1.0) 9 #define mod 1000000007 10 using namespace std; 11 int a,b; 12 struct node 13 { 14 int x; 15 int step; 16 }exm,gg; 17 queue<node> q; 18 int vis[100005]; 19 void bfs(int st) 20 { 21 memset(vis,0,sizeof(vis)); 22 while(!q.empty()) 23 q.pop(); 24 exm.x=st; 25 exm.step=0; 26 vis[st]=1; 27 q.push(exm); 28 while(!q.empty()) 29 { 30 exm=q.front(); 31 q.pop(); 32 if(exm.x==b) 33 { 34 cout<<exm.step<<endl; 35 break; 36 } 37 for(int i=1;i<=sqrt(exm.x);i++) 38 { 39 if(exm.x%i==0) 40 { 41 gg.x=exm.x+i; 42 gg.step=exm.step+1; 43 if(gg.x<=b&&vis[gg.x]==0) 44 { 45 q.push(gg); 46 vis[gg.x]=1; 47 } 48 gg.x=exm.x+exm.x/i; 49 gg.step=exm.step+1; 50 if(gg.x<=b&&vis[gg.x]==0) 51 { 52 q.push(gg); 53 vis[gg.x]=1; 54 } 55 } 56 } 57 } 58 } 59 int main() 60 { 61 while(scanf("%d %d",&a,&b)!=EOF) 62 { 63 if(a<=b) 64 bfs(a); 65 else 66 cout<<"-1"<<endl; 67 } 68 return 0; 69 }
标签:
原文地址:http://www.cnblogs.com/hsd-/p/5538606.html