zoukankan      html  css  js  c++  java
  • POJ 3278 Catch That Cow

    题意:给一个起点和终点,只有三种走法n+1, n-1, n*2, 求最短需要的步数

    解题思路:BFS,用BFS解决无权图的最短路问题。

    注:很容易re,我re了10多次,有两个点要注意

    1.如果起始点s>=终点e那么,就只能回退,所以step=s-e

    2.编号不可能出边界(0, MAXSIZE)

     1 #include <iostream>
     2 #include <cstring>
     3 #include <algorithm>
     4 #include <queue>
     5 #define MAXVERTEXNUM 1000100
     6 using namespace std;
     7 
     8 int dist[MAXVERTEXNUM];
     9 int Visited[MAXVERTEXNUM];
    10 int s, e;
    11 
    12 void BFS()
    13 {
    14     queue<int> q;
    15     q.push(s);
    16     Visited[s] = 1;
    17 
    18     while (!q.empty())
    19     {
    20         int num = q.front();
    21         if (num == e)
    22             return;
    23         q.pop();
    24 
    25         int d1 = num * 2, d2 = num + 1, d3 = num - 1;
    26         if (d1 < MAXVERTEXNUM && !Visited[d1])
    27         {
    28             dist[d1] = dist[num] + 1;
    29             q.push(d1);
    30             Visited[d1] = 1;
    31         }
    32         if (!Visited[d2])
    33         {
    34             dist[d2] = dist[num] + 1;
    35             q.push(d2);
    36             Visited[d2] = 1;
    37         }
    38         if (d3 >= 0 && !Visited[d3])
    39         {
    40             dist[d3] = dist[num] + 1;
    41             q.push(d3);
    42             Visited[d3] = 1;
    43         }
    44     }
    45 }
    46 
    47 int main()
    48 {
    49     cin >> s >> e;
    50     memset(dist, 0, sizeof(dist));
    51     memset(Visited, 0, sizeof(Visited));
    52 
    53     if (s >= e)
    54         cout << s - e << endl;
    55     else
    56     {
    57         BFS();
    58         cout << dist[e] << endl;
    59     }
    60 
    61     return 0;
    62 }
  • 相关阅读:
    观察者模式学习--使用jdk的工具类简单实现
    观察者模式的初始学习--自己实现
    反射 reflect 初始学习
    eclipse java 空心J文件的回复
    linux 命令 more
    spring 3 的 @value的使用
    linux rm 命令
    linux log find 查询
    Resource is out of sync with the file system
    JavaScript(七)数组
  • 原文地址:https://www.cnblogs.com/ducklu/p/9293324.html
Copyright © 2011-2022 走看看