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

Task

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:

1
5 17

output:

1
4

Solution

每走到一个点x,可有3种决策:-1,+1,*2,可根据此得到一棵决策树,如下图。根节点为初始位置,度为3,每个节点中存储当前位置x和当前深度step。要找到最少步数,即是决策树生长停止时的最小深度。用广度优先搜索。 用队列实现BFS,初始时将根节点放入空队列,然后将队首节点取出,算出其3个子节点,将3个子节点分别入队(保证同深度的节点连续,这样取出时也是连续取出,即广度优先)。重复这个过程,直到某个节点的x等于目的K 过程中用一个数组location来保证不走重复位置,避免陷入循环。 location=0和1分别是未走过和已经走过的位置。location的大小是允许走的最大长度。 这个最大长度是N,K取值范围[0,100000]的两倍,因为有时候需要走到K后面,再往回走。如K=100000,N=50001,则(x*2)->(x-1)->(x-1)是最短路径。 BFS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
// x may >K, for example,
// K=100000,N=50001, then
// (x*2)->(x-1)->(x-1)
// may be the best choice, 
// so MAXLEN must be large enough
const int MAXLEN=200002;
int N,K;
bool location[MAXLEN];
struct node{
    int x,step;
};
queue<node> q;
void BFS(){
    int x,step;
    int x1,x2,x3;
    while(!q.empty()){
        node n1=q.front();
        q.pop();
        x=n1.x;
        step=n1.step;
        // 3 choices of actions
        x1=x-1, x2=x+1, x3=x*2;
        if(x==K){
            printf("%d\n",step);
            return;
        }
        // 3 branches correspond to 3 branches in decision tree
        if(x>0 && location[x1]==0){
            location[x1]=1;
            node n2={x1,step+1};
            q.push(n2);
        }
        if(x<K && location[x2]==0){
            location[x2]=1;
            node n2={x2,step+1};
            q.push(n2);
        }
        if(x<K && location[x3]==0){
            location[x3]=1;
            node n2={x3,step+1};
            q.push(n2);
        }
    }
}
int main(){
    while(scanf("%d %d",&N,&K)!=EOF){
        memset(location,0,sizeof(location));
        while(!q.empty())
            q.pop();
        location[N]=1;
        node n0={N,0};
        q.push(n0);
        BFS();
    }
    return 0;
}