kuangbin专题 专题一 简单搜索 Catch That Cow POJ - 3278

 

题目链接:https://vjudge.net/problem/POJ-3278

 

题意:人可以左移动一格,右移动一格,或者移动到当前位置两倍下标的格子


思路:把题意的三种情况跑bfs,第一个到达目的地的时间最短。


 

 1 #include <iostream>
 2 #include <string.h>
 3 #include<queue>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 #define rep(i,j,k) for(int i = (j); i <= (k); i++)
 8 #define per(i,j,k) for(int i = (j); i >= (k); i--)
 9 
10 const int N = 1e5 + 10;
11 int mv[] = { -1, 1, 2 };//2表示跳跃
12 bool vis[N];
13 int n, k;
14 
15 struct node{
16     int x, c;
17 };
18 
19 //判断是否在界限内
20 inline bool check(int x){
21     return x >= 0 && x <= 100000;
22 }
23 
24 void bfs(){
25 
26     vis[n] = true;
27     queue<node> que;
28     que.push(node{n,0});
29 
30     //直接抓到
31     if (n == k){
32         cout << 0 << endl;
33         return;
34     }
35 
36     int dx;
37     while (!que.empty()){
38         node tmp = que.front();
39         que.pop();
40 
41         rep(i, 0, 2){
42             if (i == 2) dx = tmp.x << 1;//跳跃 dx = tmp.c * 2
43             else dx = tmp.x + mv[i];
44             
45             //是否在界限内且没被访问
46             if (check(dx) && !vis[dx]){
47                 vis[dx] = true;//标记访问过了
48                 
49                 //抓到了
50                 if (dx == k){
51                     cout << tmp.c + 1 << endl;
52                     return;
53                 }
54                 else que.push(node{ dx, tmp.c + 1 });
55             }
56         }
57     }
58     
59 }
60 
61 int main(){
62 
63     ios::sync_with_stdio(false);
64     cin.tie(0);
65 
66     cin >> n >> k;
67     bfs();
68 
69     return 0;
70 }
posted @ 2019-07-10 15:08  SummerMingQAQ  阅读(125)  评论(0编辑  收藏  举报