POJ 3278 Catch That Cow

题目地址

分析:

  BFS入门。搜索的门,我大概是被卡住了吧

    人抓牛,可以从任意点X移动到X -1 / X + 1 / X * 2点,耗时均为1分钟。问人抓到牛的最短时间。

看了好些个博客,https://blog.csdn.net/weiwanshu/article/details/45770537 这个的讲解很容易懂,但是是c语言版,c++可以直接用到queue模板库的队列。比较好操作。另:开一个vis数组,标记走过的点,防止无限的往下找,保证每个元素不相等。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<queue>
 5 using namespace std; 
 6 const int maxn = 100005;
 7 
 8 int vis[maxn];
 9 int cnt;
10 void bfs(int n, int k)
11 {
12     queue<int>Q;
13     Q.push(n);
14     Q.push(cnt);
15     vis[n] = 1;
16     
17     while(!Q.empty()){
18         n = Q.front();
19         Q.pop();
20         cnt = Q.front();
21         Q.pop();
22         
23         if(n == k) return;
24         if(n-1 >= 0 && !vis[n-1]){
25             Q.push(n-1);
26             Q.push(cnt+1);
27             vis[n-1] = 1;
28         }
29         if(n+1 < maxn && !vis[n+1]){
30             Q.push(n+1);
31             Q.push(cnt+1);
32             vis[n+1] = 1;            
33         }
34         if(n*2 < maxn && !vis[n*2]){
35             Q.push(n*2);
36             Q.push(cnt+1);
37             vis[n*2] = 1;
38         }
39     }
40 }
41 int main()
42 {
43     int n, k;
44     while(cin >> n >> k){
45         if(n >= k){
46             cout << n - k << endl;
47             continue;
48         }
49         cnt = 0;
50         memset(vis,0,sizeof(vis));
51         bfs(n, k);
52         cout << cnt << endl;
53     }
54     return 0;
55 }

 

原文地址:https://www.cnblogs.com/JiaaaaKe/p/9512645.html