poj3278Catch That Cow

出自http://acm.hrbust.edu.cn/vj/index.php?c=problem-problem&id=291712

  题意:给你两个数N和K,N每次可以进行+1,-1,*2的运算, 问你最少几次N可以变成K。BFS搜索

  

 1 #include <iostream>
 2 #include <queue>
 3 #include <cstring>
 4 using namespace std;
 5 const int MAX = 200030;//这里数组要开大点。RE的半天
 6 int deep[MAX];
 7 int visit[MAX];
 8 queue<int> q;
 9 int n, k;
10 int BFS()
11 {
12    while(!q.empty()){
13           q.pop();
14      }
15      q.push(n);
16      visit[n] = 1;
17      deep[n] = 0;
18 
19     while(!q.empty()){
20           int temp = q.front();
21             q.pop();
22           visit[temp] = 1;
23           int x = temp-1;
24           int y = temp+1;
25           int z = 2*temp;
26           if(temp == k)
27              break;
28           else{
29           if(x>=0 && !visit[x]){
30               deep[x]=deep[temp]+1;
31               q.push(x);
32               visit[x] = 1;
33 
34           }
35           if(y<=100000&& !visit[y]){
36                     deep[y]=deep[temp]+1;
37                     q.push(y);
38                     visit[y] = 1;
39 
40           }
41           if(z<=100000&& !visit[z]){
42                     deep[z]=deep[temp]+1;
43                     q.push(z);
44                     visit[z]= 1;
45           }
46       }
47 
48     }
49    return deep[k];
50 }
51 
52 int main()
53 {
54        while(cin >> n >> k){
55       memset(deep, 0, sizeof(deep));
56       memset(visit, 0, sizeof(visit));
57       cout << BFS() << endl;
58        }
59 
60 return 0;
61 }
View Code

 

posted @ 2014-08-04 22:47  tt_tt--->  阅读(64)  评论(0编辑  收藏  举报