水题,搜索一个数转化成另一个数。
1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 using std::queue; 5 #define N 100010 6 int d[N]; 7 bool vis[N]; 8 int m,n,a; 9 int nxt(int x) 10 { 11 int t; 12 if(x==0) t = a-1; 13 else if(x==1) t=a+1; 14 else t = a<<1; 15 return t; 16 } 17 int bfs() 18 { 19 if(m==n) return 0; 20 int b,i; 21 memset(vis,0,N); 22 queue <int> q; 23 q.push(m); 24 d[m] = 0; 25 vis[m] = 1; 26 while(!q.empty()) 27 { 28 a = q.front(); 29 q.pop(); 30 for(i = 0; i < 3; i++) 31 { 32 b = nxt(i); 33 if(b >= 0 && b <= 100000 && !vis[b]) 34 { 35 if(b == n) return d[a]+1; 36 q.push(b); 37 vis[b] = 1; 38 d[b] = d[a]+1; 39 } 40 } 41 } 42 return -1; 43 } 44 int main() 45 { 46 while(~scanf("%d%d",&m,&n)) 47 printf("%d\n",bfs()); 48 return 0; 49 }