zoukankan      html  css  js  c++  java
  • POJ3278 Catch that cow

    Description

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

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

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

    Input

    N和K

    Output

    最短的时间

    题解:是一道bfs的入门题,注意只有向左走一步才能往左走,注意添加if(k<n)printf("%d ",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-k);
    48         return 0;
    49     }
    50     bfs(n);
    51     printf("%d
    ",step[k]);
    52     return 0;
    53 }
  • 相关阅读:
    AjaxHelper 无刷新留言
    girdview 中的radiobutton 的逐行触发checkedselected事件
    .NET 新语法
    获取checkbox的值
    git 代码提交规范
    chrome的timeline中stalled问题解析
    小程序添加节流阀
    深度遍历与广度遍历
    JS 运行机制
    地址栏输入url后做了那些事情什么
  • 原文地址:https://www.cnblogs.com/Hoyoak/p/11634932.html
Copyright © 2011-2022 走看看