Live2D

POJ3278 Catch that cow

Description

在一个数轴上开始农夫在位置N,奶牛在位置K,奶牛的位置不动,农夫每次有三种选择:

1,向左走一步,花费1秒 2,向右走一步,花费一秒 3,走到2*n的位置,花费一秒

问农夫最少花多长时间找到奶牛。

Input

N和K

Output

最短的时间

 

题解:是一道bfs的入门题,注意只有向左走一步才能往左走,注意添加if(k<n)printf("%d\n",n-k);的剪枝。

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 #define maxn 1000005
 7 
 8 using namespace std;
 9 
10 int step[maxn],n,k;
11 bool vis[maxn];
12 queue <int> q;
13 
14 inline void bfs(int pos)
15 {
16     step[pos]=0;
17     vis[pos]=true;
18     q.push(pos);
19     while(!q.empty())
20     {
21         int p=q.front(); q.pop();
22         for(register int i=1;i<=3;++i)
23         {
24             int nxt;
25             if(i==1) nxt=p+1;
26             else if(i==2) nxt=p-1;
27             else if(i==3) nxt=p*2;
28             if(nxt<0||nxt>=maxn) continue;
29             if(!vis[nxt])
30             {
31                 step[nxt]=step[p]+1;
32                 vis[nxt]=true;
33                 q.push(nxt);
34             }
35             if(nxt==k) return;
36         }
37     }
38     return;
39 }
40 
41 int main()
42 {
43     while(!q.empty()) q.pop();
44     scanf("%d%d",&n,&k);
45     if(n>=k)
46     {
47         printf("%d\n",n-k);
48         return 0;
49     }
50     bfs(n);
51     printf("%d\n",step[k]);
52     return 0;
53 }

 

posted @ 2019-10-08 13:28  Hoyoak  阅读(113)  评论(0编辑  收藏  举报