POJ 3278(Catch That Cow)

 1 /* BFS入门题
 2 思路:以n为始点开始搜索,直到搜到k为止
 3 注意需剪枝,否则会超时,剪枝最重要的一点就是: 
4
已经入队过得点不许再重复入队 5 */
6 #include<iostream> 7 #include<queue> 8 using namespace std; 9 bool flag[200005]; 10 struct node 11 { 12 int x,t; 13 }; 14 void BFS(int n,int k) 15 { 16 queue<node> q; 17 node a; 18 memset(flag,false,sizeof(flag)); 19 a.x = n; 20 a.t = 0; 21 q.push(a); 22 flag[n] = true; 23 while(!q.empty()) 24 { 25 node temp = q.front(); 26 q.pop(); 27 node next; 28 if(temp.x-1 == k) 29 { 30 printf("%d\n",temp.t+1); 31 return; 32 } 33 if(temp.x >= 1 && !flag[temp.x-1]) 34 { 35 next.x = temp.x-1,next.t = temp.t+1; 36 q.push(next); 37 flag[temp.x-1] = true; 38 } 39 if(temp.x+1 == k) 40 { 41 printf("%d\n",temp.t+1); 42 return; 43 } 44 if(temp.x <= k && !flag[temp.x+1]) 45 { 46 next.x = temp.x+1,next.t = temp.t+1; 47 q.push(next); 48 flag[temp.x+1] = true; 49 } 50 if(temp.x * 2 == k) 51 { 52 printf("%d\n",temp.t+1); 53 return; 54 } 55 if(temp.x < k && !flag[temp.x*2]) 56 { 57 next.x = temp.x*2,next.t = temp.t+1; 58 q.push(next); 59 flag[temp.x*2] = true; 60 } 61 } 62 } 63 int main() 64 { 65 int n,k; 66 //freopen("3278.txt","r",stdin); 67 while(scanf("%d%d",&n,&k) != EOF) 68 { 69 if(n == k) 70 { 71 printf("0\n"); 72 continue; 73 } 74 BFS(n,k); 75 } 76 return 0; 77 }

 

posted @ 2012-09-27 11:33  sorryhao  阅读(141)  评论(0)    收藏  举报