POJ - 3278(BFS)

来源:互联网 发布:藏剑正太捏脸数据 编辑:程序博客网 时间:2024/05/17 09:37

Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
Source
USACO 2007 Open Silver

题意:一个农夫去找牛,他现在在n处,牛在k处,农夫有两种移动方式,一种是到x-1或x+ 1,另一种是直接到x * 2,每一种移动方式移动时间都是1分钟,问农夫到达牛所在位置最少需要多长时间。

题解:这道题由于移动方式的移动时间相同,所以可以用BFS,一层层找,下一层比本层的时间多一,直到走到目标点。具体扩展层数的方法是:先把初始节点压入队列,把能从初始节点到达的点也压入队列,第一层就是初始节点所能到达点,下一层是把队列中元素依次出队,把他们所能到达的点也压入队列,构成下一层,一直往下构造,直到到达目标节点。此处需要注意,0 ≤ K ≤ 100,000,所以要判断边界。

思考:
1、一定要先判断边界再往下走,而且边界具体是什么要准确。

#include <iostream>#include <cstdio>#include <string>#include <algorithm>#include <cstring>#include <cmath>#include <vector>#include <map>#include <set>#include <queue>using namespace std;const int INF = 1 << 30;const int maxn = 100000;int n, k, vis[maxn + 10], mintime[maxn + 10];void BFS(){    queue<int> q;    q.push(n);    vis[n] = 1;    mintime[n] = 0;    while (!q.empty()) {        int now = q.front(); q.pop();        if (now == k) {            break;        }        int x1 = now - 1, x2 = now * 2, x3 = now + 1;        if (x1 >= 0 && !vis[x1]) {//要先判断边界再继续判断,且边界为>=0,因为0 <=k <= maxn,0可以取            vis[x1] = 1;            mintime[x1] = mintime[now] + 1;            q.push (x1);        }        if (x2 <= maxn && !vis[x2]) {//只有maxn个节点,所以边界是maxn,不能是别的            vis[x2] = 1;            mintime[x2] = mintime[now] + 1;            q.push (x2);        }        if (x3 <= maxn && !vis[x3]) {            vis[x3] = 1;            mintime[x3] = mintime[now] + 1;            q.push (x3);        }    }}int main(){    #ifndef ONLINE_JUDGE    freopen ("in.txt", "r", stdin);    #endif // ONLINE_JUDGE    scanf ("%d%d", &n, &k);    memset (vis, 0, sizeof(vis));    BFS ();    printf ("%d\n", mintime[k]);    return 0;}
0 0
原创粉丝点击